views:

395

answers:

2

Hi,

I've extended the ByteArray class, like this:

[RemoteClass(alias="MyByteArray")]
public class MyByteArray extends ByteArray {}

and cloned an instance of this class using ByteArray#readObject()/writeObject(). However, for some reason, the cloned object is an instance of ByteArray rather than MyByteArray. This is illustrated in the following example:

registerClassAlias("MyByteArray", MyByteArray);
var b1:MyByteArray = new MyByteArray();
var tmp:ByteArray = new ByteArray();
tmp.writeObject(b1);           
tmp.position = 0;
var b2:* = tmp.readObject();
trace( b2 is MyByteArray ); // prints false
trace( b2 is ByteArray ); // prints true

Moreover, when I add some custom fields in MyByteArray class, they aren't saved with writeObject() and neither cloned...

Can anybody explain me why the cloned object is not an instance of MyByteArray?

Thanks a lot!

+1  A: 

I think this is because tmp is of type ByteArray, not of type MyByteArray. If you make tmp of type MyByteArray, it should return an object of the same type, using writeObject i think? Or you may need to typecast it.

quoo
No, tmp needs to be of type ByteArray. This is the typical way of cloning objects in AS3, implemented also as ObjectUtil.copy(). Typecasting doesn't help as tmp.writeObject() doesn't save any fields of MyByteArray (in this minimal example MyByteArray has no fields, but it has in my application). The weird thing is that if MyByteArray does not extend ByteArray, then everything works OK, i.e., b2 is of type MyByteArray after cloning.
bartekb
A: 

ByteArray is likely handled as a special case for object serialisation, so I doubt you'll get around it.

Attempting to subclass ByteArray sounds like a code smell to me. I'd look at using encapsulation rather than inheritance to solve your problem.

Richard Szalay
Thanks for input. I intentionally used inheritance and not encapsulation as I was trying to trick Flash Player a bit... I was trying to pass MyByteArray instead of ByteArray as an argument to FileReference#save(), hoping that I could "stream" data to a local file rather than write the whole file at once (MyByteArray would be producing data in real-time). I've described this problem here: http://stackoverflow.com/questions/869816/filereference-save-duplicates-bytearray
bartekb
Try implementing IDataInput on your object. Failing that, the only solution I know of is AIR-only (FileStream)
Richard Szalay
After reading up about it, it looks like you will need to stream your content into a ByteArray (which implements IDataOutput) and then save that instance of ByteArray. When reloading, you can read from it (it also implements IDataInput).
Richard Szalay
My content is larger than the available memory, so I can't stream the whole content to the in-memory ByteArray. I need to stream it directly (or in chunks) to a file, much as in the FileStream class (AIR-only). However, it seems to me that it's not possible in Flash 10...
bartekb