问题
I'm trying to load an array that contain some display objects, the program lets me to populate the array with circles and save them to a shared object, then, I can trace the content of my array using the load button. The problem is that i can't load the array after that I restart my program. It traces me this message:"objects loaded: ,,,"
This is the code:
var SO:SharedObject=SharedObject.getLocal("myFile", "/");
var arr:Array=new Array();
var counter:Number=-1;
addBtn.addEventListener(MouseEvent.CLICK, addObjects);
saveBtn.addEventListener(MouseEvent.CLICK, saveObjects);
loadBtn.addEventListener(MouseEvent.CLICK, loadObjects);
function addObjects(event:Event) {
counter++;
var circle:circleClip=new circleClip();
arr.push(circle);
trace("current object: "+arr[counter]);
}
function saveObjects(event:Event) {
SO.data.arrSaved=arr;
SO.flush();
trace("objects saved: "+SO.data.arrSaved);
}
function loadObjects(event:Event) {
var arrLoaded:Array=new Array();
arrLoaded=SO.data.arrSaved;
trace("objects loaded: "+arrLoaded);
}
回答1:
You are to understand MVC pattern approach: https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
You need to separate data from the code that visualizes things out of these data, and store data only. Something like:
// Lets say this Array contains a list of your circle objects.
var Curcus:Array;
// Storage.
var SO:SharedObject = SharedObject.getLocal("myFile", "/");
function saveCircus():void
{
var aList:Array = new Array;
aList.length = Circus.length;
for (var i:int = 0; i < Curcus.length; i++)
{
// Get an object.
var aCircle:Sprite = Curcus[i];
// Record its properties you want to store.
var anEntry:Object =
{
"x":aCircle.x,
"y":aCircle.y,
"scaleX":aCircle.scaleX,
"scaleY":aCircle.scaleY
};
// Store the entry.
aList[i] = anEntry;
}
// Store and save data.
SO.data.arrSaved = aList;
SO.flush();
}
function loadCircus():void
{
// Retrieve saved data.
var aList:Array = SO.data.arrSaved;
// Make it empty data if there are none.
if (!aList) aList = new Array;
Circus = new Array;
Curcus.length = aList.length;
for (var i:int = 0; i < aList.length; i++)
{
// Get one entry.
var anEntry:Object = aList[i];
// Create a new item. BTW, naming classes with the
// lowercase first letter is the 8th cardinal sin.
var aCircle = new CircleClip;
// Restore saved properties.
aCircle.x = anEntry['x'];
aCircle.y = anEntry['y'];
aCircle.scaleX = anEntry['scaleX'];
aCircle.scaleY = anEntry['scaleY'];
// Add to display list.
addChild(aCircle);
// Keep it for the future reference/saving.
Curcus[i] = aCircle;
}
}
来源:https://stackoverflow.com/questions/43686854/loading-array-of-display-objects-using-shared-objects-in-action-script-3-0