ArrayCollection.setItemAt正在做一些有趣的事

问题描述:

我想用此代码交换ArrayCollection中的两个项目。ArrayCollection.setItemAt正在做一些有趣的事

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(); 
} 

在调试代码中,我可以看到curItem和swapItem是正确的对象,但是当我做我的第一setItemAt,它取代了一个,我想也是一个我没有想。有什么想法发生在这里?

这是因为调用getItemAt来设置curItem和swapItem结果引用ArrayCollection中的对象而不是对象本身。当你用第一个setItemAt改变对象时,你的引用也会改变。在这一点上,curItem和swapItem可能都指向同一个对象。我会以不同的方式处理,并使用removeItemAt和addItemAt来代替,这样您就可以使用对象而不是引用。希望有所帮助。

+0

+1因为这次你打败了我。 ;) – JeffryHouser 2010-10-12 03:04:33