actionscript-3apache-flexserializationdeserializationamf

Flex - saving Serialized ArrayCollection of Objects to File


Creating class with RemoteClass metateg

[RemoteClass]
public class Result 
{
    public function Result(){} 
}

Function for writing in file

public function writeData(object:Object):void
{
    var file:File = File.desktopDirectory.resolvePath("data.txt");
    if (file.exists)
        file.deleteFile();      
    var fileStream:FileStream = new FileStream();
    fileStream.open(file, FileMode.WRITE);
    fileStream.writeObject(object);
    fileStream.close();
}

Function for reading from file

public function readData():Object
{
    var file:File = File.desktopDirectory.resolvePath("data.txt");
    if(!file.exists) 
        return 0;
    var fileStream:FileStream = new FileStream();
    fileStream.open(file, FileMode.READ);
    var obj:Object = fileStream.readObject();
    fileStream.close();
    return obj;
}

Function when application initializing

public function initApplication():void
{
    writeData(new Result()); // write object to file.
    var result:Result = readData() as Result; // create Result class object and initializing it data from file
    var array:ArrayCollection = new ArrayCollection(); // create collection and fill it objects of Result class
    array.addItem(new Result());
    array.addItem(new Result());
    array.addItem(new Result());
    writeData(array); // writing collection in file
    var arr:ArrayCollection = readData() as ArrayCollection; // initializing new collecion of collection from file.
}

Here is the problem. Returned collection with objects of Object type. How can I get collection of Result type objects? Bad way below

for each (var object:Object in arr) 
{
        object = object as Result;
}

Solution

  • Use registerClassAlias() before serialization/deserialization