views:

31

answers:

1

I am trying to swap two items in an ArrayCollection with this code.

private function swapCollectionElements(collection:ArrayCollection, fromIndex:uint, toIndex:uint) : void 
{
    var curItem:Object = collection.getItemAt(fromIndex);
    var swapItem:Object = collection.getItemAt(toIndex);

    collection.setItemAt(curItem, toIndex);
    collection.setItemAt(swapItem, fromIndex);

    collection.refresh();
}

When debugging the code I can see that curItem and swapItem are the correct objects, but when I do my first setItemAt, it replaces the one I wanted but also one that I didnt want. Any ideas what is going on here?

+1  A: 

This is because calling getItemAt to set curItem and swapItem results in references to the objects in the ArrayCollection rather than the objects themselves. When you change the object with your first setItemAt, your reference changes as well. At that point both curItem and swapItem probably refer to the same object. I would approach this differently and use removeItemAt and addItemAt instead, that way you are working with the objects rather than references. Hope that helps.

Wade Mueller
+1 because this time you beat me to it. ;)
www.Flextras.com