Deep Copy an Array of Typed Value Objects

I recently needed to copy an Array of nested Value Objects and discovered a couple of issues that I thought I should blog about, for my own future reference if anything (memory ain’t what it used to be). A method such as:

1
2
3
4
5
6
7
8
9
10
11
var my_arr:Array    = clone( old_arr ) as Array;

private function clone( source:Object ):*
{
    var myBA:ByteArray = new ByteArray();
              
    myBA.writeObject( source );
    myBA.position = 0;
              
    return( myBA.readObject() );
}

… will strip your typed objects. ObjectUtil.copy will perform a deep copy but will also strip the object type, the solution is good ol’ registerClassAlias() e.g.

1
2
3
registerClassAlias( "com.newtriks.model.vo.CustomVO", CustomVO ); 

var my_arr:Array    = ObjectUtil.copy( old_arr ) as Array;

For nested typed objects within the array’s value objects then simply ensure your register its class alias.

Please read this more informative post on the subject Darron Schall

Comments