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
Jodie's Twitter
Popular categories:
Recent posts:
- I'll be at Adobe MAX
- Flash Camp Birmingham
- Flash Media Playback launches
- Flash Builder to Android workflow
- Strobe Media Playback presentation
- Flash Camp Manchester
- Welcome OSMF 1.0!
- Get the best out of blinkbox on PS3
- H.264 Flash Lite 3.1 on Nintendo Wii
- OSMF plug-in example
- more...
Places you'll find me:
Archive:
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2009
- December 2009
- November 2009
- October 2009
- September 2009
