Cloning ArrayCollection
Posted: 14/04/09
There are plenty of occasions where you might want to be able to create an exact clone of a complex/nested data objects, without your new object simply referencing the old one's values. To do this, you need to force the creation of new values and references. Depending on the complexity of the data stored, this will be achieved through shallow or deep copying:
Shallow Copy
Fine if your collection only contains values and references that can be shared/reused around the app:
var newAC:ArrayCollection = new ArrayCollection( originalAC.source ) );
Deep Copy
Heavier going; but as well as creating cloned values, it creates new references (pointers) for everything too. Only really necessary if you don't want your new object to hold the same object references that your old one did:
private function clone( source:Object ) :*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject( source );
myBA.position = 0;
return( myBA.readObject() );
}
var newAC:ArrayCollection = new ArrayCollection( clone( originalAC.source ) );
The clone method in the code above can be used for cloning just about any object (including deep copying of ByteArray), and would make a good utility method in any custom framework (both within or outside of the Flex framework). Please note that readObject() will not work with Flash DisplayObjects; however, it will work with complex objects derived from simple types.
The Flex frameworks includes the ObjectUtil that allows you to perform a clean copy using the copy() method.
var myAC:ArrayCollection = new ArrayCollection( ObjectUtil.copy( originalAC.source ) as Array );
Acknowledgement: Thanks to Daniel Jarvis for sharing some of his thoughts on this subject with me.
Keywords for this post: clone, duplicate, copy, ArrayCollection, Array, data, objects, actionscript 3, flex, bytearray
Popular categories:
- Video |
- Mobile |
- OSMF |
- ActionScript
Books:
Recent posts:
Eclipse: An error has occurred. See the log file .metadata/.log
Updated blinkbox iPad app
Nexus 7 doesn't appear in adb devices list
Improve the keyboard in the Samsung ICS update
403 Forbidden error on Mac web server
Getting error with manually created NIB?
Adding/removing items from PATH on Mac
Presenting at Flash Oxford
Failed to get the task for process xx
OSX: Fix for network accounts unavailable- more...
Places you'll find me:
Archive:
- April 2013
- March 2013
- February 2013
- January 2013
- December 2012
- November 2012
- October 2012
- September 2012
- August 2012
- July 2012
- June 2012
- May 2012
