使用flash.net.registerClassAlias( )方法保留類型信息並把類實例添加到共享對象的data屬性上。編碼
LSOs 使用特殊的二進制格式,Action Message Format (AMF),當要在LSO中存儲類實例時,實例會被編碼爲包含屬性的普通的object。這樣當從新從共享對象中讀取實例時,已經不是原來的類實例了,由於已不能根據類型信息解碼回來。spa
下面的例子完整實現了類實例的保存,首先建立自定義類:.net
package model { public class Person { private var _firstName:String; private var _age:int; public function Person(firstName:String, age:int) { _firstName = firstName; _age = age; } public function toString( ):String { return _firstName + " is " + _age + " years old"; } } }
接着,編寫主類讀取和寫入數據code
package
{ import flash.net.registerClassAlias; import flash.net.SharedObject; import model.Person; public class Example
{ public function Example( )
{ registerClassAlias( "model.Person", Person ); var example:SharedObject = SharedObject.getLocal( "example" ); if ( example.data.person == undefined )
{ trace( "first time, saving person instance" ); var person:Person = new Person("Darron", 24); example.data.person = person; } else { trace( "person instance already saved, using stored values" ); } trace( example.data.person.toString( ) );
}
} }
這裏須要注意的是registerClassAlias( )必須在SharedObject.getLocal( )方法以前調用纔有效。不然的話共享對象會把Person解釋爲普通的object類型進行存儲。orm