我只是尝试使用flex共享对象功能保存一些数据。数据已成功保存,但当我将其检索回来时,我无法将其强制转换回原始对象。例如,我正在保存我的自定义类的对象,当我检索它时,它是Object类型。虽然我在检查时调试模式,但它包含我的自定义类的所有成员及其值。但是我无法将它从Object类型转换回我的自定义类。
有人可以帮我吗?
答案 0 :(得分:3)
你可以使用registerClassAlias
registerClassAlias("com.path.to.MyClass", MyClass);
myStuff = SharedObject.getLocal("myAppStuff");
myStuff.data.whatINamedIt = myClassInstance;
myStuff.flush();
现在什么时候回来......你可以说:
myStuff = SharedObject.getLocal("myAppStuff");
var mySavedClass:MyClass = myStuff.data.whatINamedIt as MyClass;
答案 1 :(得分:1)
您的自定义类必须实现IExternalizable
在获取共享对象之前,您必须使用registerClassAlias
private var so:SharedObject;
private function writeMyCustomClass():void
{
registerClassAlias("classes.MyCustomClass", MyCustomClass);
so = SharedObject.getLocal("savedCustom");
so.clear();
var mycustom:MyCustomClass = new MyCustomClass;
mycustom.name = "Raja";
mycustom.age = 27;
so.data.custom = getAndwriteCustomClassToByteArray(mycustom).readObject();
so.flush();
}
private function getAndwriteCustomClassToByteArray(mycustom:MyCustomClass):ByteArray
{
var copier:ByteArray = new ByteArray();
copier.position=0;
copier.writeObject(mycustom);
copier.position=0;
return copier;
}
private function getMyCustomClass():void
{
registerClassAlias("classes.MyCustomClass", MyCustomClass);
so = SharedObject.getLocal("savedCustom");
var mycustom:MyCustomClass = so.data.custom;
}
package
{
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
public class MyCustomClass implements IExternalizable
{
public var name:String;
public var age:int;
public function MyCustomClass()
{
}
public function writeExternal(output:IDataOutput):void {
output.writeObject(this.name);
output.writeInt(this.age);
}
public function readExternal(input:IDataInput):void {
this.name=input.readObject();
this.age=input.readInt();
}
}