Question

I know that if I want to store a custom class with SharedObject, I have to use registerClassAlias.

registerClassAlias("MyClass", MyClass);
sharedObject.data.myObject = new MyClass();

But in my case, I have a custom class whose fields are themselves instances of custom classes. How can I store it in such a way as to recover the types when I load the data?

Specifically, the class in question is a Graph class which contains an array of Objects. This isn't the actual code, just an overview:

class Graph {
    public var vertices : Array;
}

I have an instance of this Graph class, and I'm filling its vertices field with instances of another class, called Node. I need to store this Graph instance in such a way that I can:

  1. Recover it as a Graph instance.
  2. Access the vertices field of this recovered instance, and then access the elements of that array as Node types.

I've tried throwing some registerClassAlias("Node", Node)'s in appropriate-seeming places, but it's not having any effect. Is there a way to do this?

Was it helpful?

Solution

With more complex data such as this, your best bet is to define load() and save() methods manually on objects that you want to store in a SharedObject. Those methods will define what data should be saved, simplified as much as possible, and collate it into a format of your choice such as JSON.

In this example, your Graph could have a method save() which looks like this:

public function save(name:String, sharedObject:SharedObject):void
{
    var list:Array = [];
    for each(var node:Node in vertices)
    {
        // Add a simple object defining the important Node properties
        // to the array we will save as JSON.
        list.push({ x: node.x, y: node.y });
    }

    sharedObject.data[name] = JSON.encode(list);
}

And then a load() function like so:

public function load(name:String, sharedObject:SharedObject):void
{
    // Empty current list of vertices.
    vertices = [];

    var list:Array = JSON.decode(sharedObject.data[name]);
    for each(var def:Object in list)
    {
        // Create real Node from simpler definition.
        var node:Node = new Node();

        node.x = def.x;
        node.y = def.y;
        vertices.push(node);
    }
}

Which would be utilized like:

existingGraph.save('myGraph', sharedObject);

var newGraph:Graph = new Graph();
newGraph.load('myGraph', sharedObject);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top