问题描述
读取自定义对象的字节数组时出现问题.任何帮助表示赞赏
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.
推荐答案
您想要做的是使用 registerClassAlias 方法将类型信息与数据一起注册.这样 Flash 就会知道如何序列化/反序列化您的对象.这是 Adobe 文档中的一些示例代码:
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.
这篇关于AS3 自定义对象到 ByteArray 然后到自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!