hi Is it possible to serialize a display object with ByteArray to store and recover it back ? Flash , ActionScript3 Thanks for help.
Here's a code example
import flash.display.Sprite;
import flash.utils.ByteArray;
import flash.display.Graphics;
var savedData:SharedObject = SharedObject.getLocal("savedData");
var sprite:Sprite = new Sprite();
sprite.graphics.beginFill(0xFF0000, 0.5);
sprite.graphics.drawRect(0, 0, 40, 40);
this.addChild(sprite);
// first run
if (!savedData.data.spriteData) {
sprite.x = 100 + Math.random()*300
sprite.y = Math.random()*300
sprite.rotation = Math.random()*90;
sprite.scaleX = sprite.scaleY = 0.5 + Math.random();
savedData.data.spriteData = new ByteArray();
savedData.data.spriteData.writeObject(sprite);
}else {
var sd:Object = savedData.data.spriteData.readObject();
for (var s in sd) {
try {
sprite[s] = sd[s];
} catch (e:Error) {
trace("ERROR "+e);
}
}
}
On the first run it randomly places a sprite on stage. Then it saves the Display Object in AMF format as a ByteArray in a SharedObject. On second run it tries to assign each value from the saved ByteArray Object to the Sprite on scene. This however is faulty and it only works for the properties that were not references. For other complex types it throws a type coercion error.
So. You can store data as a ByteArray, but you'll have to properly instantiate the object after. I would make my own DataStoringObject for saving only the necessary properties for instantiation, and then an instantiation method that would read the byte Array object and take care of placing the object on stage.
you'd typically implement IExternalizable ... and then you can simply serialize it with any native serialization method ...
there are certain things, you'll never be able to serialize, as the graphics in a Shape
/Sprite
, etc. ... for library objects, this could be ok, for loaders, if you subclass them and override some methods, you will also be able to track load operations and restore them after deserialization ... as long as ANYTHING you want serialize is ISerializable, you have good chances to succeed in fully storing and recovering the state (except graphics, as i said) ...
and don't forget to use registerClassAlias, to be sure your classes are conserved ...
good luck then ... ;)