Cloning Arrays and Cutoms Classes in AS3
Posted by admin on June 18th, 2009
Cloning an array using concat will not clone the Objects contained by the array. Cloning with concat and then modifying one of the object will be modified in both arrays because the array contains references to the same object. That’s why we need to do a deep copy of the array, like in the following function.
/**
* will do a deep copy of the Object
*/
public static function deepClone(source:Object):*{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}The above function will clone the Array and all the objects that are contained, however it has a major disadvantage. Custom Objects contained in the cloned array will lose their class definition and array[i] as CustomClassVO will give null. This is hapening because during the deep copy the objects loose their class association. To prevent this, the following line(s) has to be added just before doing the deep copy:
import flash.net.registerClassAlias; registerClassAlias("com.client.vo.CustomClassVO", CustomClassVO);
Now, there is a more easy way to handle deep copy without loosing the custom class definition, just add the following line just before your custom class definition
[RemoteClass] /*this will help cloning the item and retaining class information*/ public class CustomClassVO{ public var variableName:String = ''; public var variableValue:Object; public function CustomClassVO(pVariableName:String = '', pVariableValue:Object = null){ variableName = pVariableName; variableValue = pVariableValue; } }
Noticed the [RemoteClass] ? It does all the job, now copying an array of CustomClassVO’s using the deepClone() is simple.