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:
Recent posts:
- Mac OS find files using regex
- ADB device driver won't install
- 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
- more...
Publications:
Places you'll find me:
Archive:
- March 2024
- February 2024
- January 2024
- December 2023
- November 2023
- October 2023
- September 2023
- August 2023
- July 2023
- June 2023
- May 2023
- April 2023