ArrayCollection.setItemAt is doing some funny things
I am trying to swap two items in an ArrayCollection with this code.
private function swapCollectionElements(collection:ArrayCollection, fromIndex:u开发者_JAVA百科int, 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?
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.
精彩评论