Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 Custom Object to ByteArray then to Custom Object

Having problem reading bytearray of custom objects. Any help is appreciated

public class CustomObject extends Object {
public function CustomObject() {
public var _x:Number =  100
public var _y:Number = 10
public var _z:Number  = 60
}
}

var cObj:CustomObject = new CustomObject()
var bytes:ByteArray = new ByteArray()
bytes.writeObject(cObj)
bytes.compress()

//read
try { bytes.uncompress() } catch (e:Error) { }
var obj:CustomObject = bytes.readObject() as CustomObject

trace(obj) // null why?!
trace(obj._z) // Obviously - TypeError: Error #1009: Cannot access a property or method of a null object reference. 
like image 734
kornesh Avatar asked Sep 18 '10 09:09

kornesh


2 Answers

What you want to do is use the registerClassAlias method to register type information along with the data. That way Flash will know how to serialize/deserialize your object. Here's some sample code from Adobe's documentation:

registerClassAlias("com.example.eg", ExampleClass);
var eg1:ExampleClass = new ExampleClass();
var ba:ByteArray = new ByteArray();
ba.writeObject(eg1);
ba.position = 0;
var eg2:* = ba.readObject();
trace(eg2 is ExampleClass); // true

It should be noted that all types that should be serialized must be registered for the type information to be saved. So if you have another type that is referenced by your type, it too must be registered.

like image 135
Marcus Stade Avatar answered Sep 22 '22 20:09

Marcus Stade


Your CustomObject class is wrong , it should throw an error actually , it should be this instead

public class CustomObject 
{
   public var _x:Number =  100
   public var _y:Number = 10
   public var _z:Number  = 60

   public function CustomObject() 
   {
   }
}

Edit:

Sounds like macke has a point, because this works...


//read
try { bytes.uncompress() } catch (e:Error) { }
var obj:Object = bytes.readObject();

trace(obj) // [object Object]
trace(obj._z) // 60
like image 23
PatrickS Avatar answered Sep 22 '22 20:09

PatrickS