views:

410

answers:

2

I know it is a simple matter to store Strings and Numbers with a SharedObject, and I am also familiar with this sort of thing:

var sharedObject:SharedObject = SharedObject.getLocal("userData");
var obj:Object = new Object();
obj.prop = "value";
sharedObject.data.userobj= obj;
sharedObject.flush();

However, I am attempting to store an object of the class GameStage, a class I have defined to hold data about stages in my game. This type of thing doesn't seem to be working:

var sharedObject:SharedObject = SharedObject.getLocal("userData");
var stageOne:GameStage = new GameStage();
stageOne.highScore = 99999;
sharedObject.data.stageOne = stageOne;
sharedObject.flush();

This code doesn't throw an error, but when I try to retrieve the stage data later, like so:

stageOne = sharedObject.data.stageOne;

I get this error:

TypeError: Error #1034: Type Coercion failed: cannot convert Object@3d220629 to GameStage.

I guess my question is: exactly what sort of data types can be stored in a SharedObject? Everywhere I've looked online has answered that question with "anything that can be used in Flash", which isn't very descriptive – obviously my GameStage class works in Flash too. Is there something about retrieving data from the SharedObject that I'm not aware of?

My prediction is that I will not be able to store my stage data this way. If that is the case, could anyone suggest an alternative method to saving the data?

+3  A: 

You can store any object in a SharedObject, but you need to register the class first:

You can store typed ActionScript instances in shared objects. You do this by calling the flash.net.registerClassAlias() method to register the class. If you create an instance of your class and store it in the data member of your shared object and later read the object out, you will get a typed instance. By default, the SharedObject objectEncoding property supports AMF3 encoding, and unpacks your stored instance from the SharedObject object; the stored instance retains the same type you specified when you called the registerClassAlias() method.

One caveat is that storing object graphs can sometimes lead to storage issues. There is a limit to how much you can store in SharedObject before it notifies the user and asks for permission to store more. This threshold is 100k by default, I believe.

Joel Hooks
A: 

If you are using Flex Builder SDK or Flex Builder you can also use the [RemoteClass] metatag which will automatically register the class and make it serializable.

sksizer