Is it possible not to flush sharedobject on close? - actionscript-3

I'm having a problem with the sharedObject flush method. Is it possible to not flush the new data when the swf is closed? My savegame function is the only function that calls the flush method and it also determines which array goes where in the sharedObject data.
parentMC.sharedObject.data.moveSpdUpgrade = parentMC.upgrades.tempMoveSpdUpgrade;
parentMC.sharedObject.flush();
However, when I modify the tempMoveSpdUpgrade array, it also saves the new data in the sharedObject even if the flush hasn't been called yet.
tempMoveSpdUpgrade[0][2] = 1;
trace(parentMC.sharedObject.data.moveSpdUpgrade);
This trace shows that the data has changed but I don't understand since the flush hasn't been called and the swf hasn't been closed. I'm wondering why the modifications made in the array automatically changes the sharedObject data.
Thank you for the help.
Edit:
public function saveGame(){
parentMC.sharedObject.data.money = parentMC.money;
parentMC.sharedObject.data.moveSpdUpgrade = parentMC.upgrades.tempMoveSpdUpgrade;
parentMC.sharedObject.flush();
}
Like I stated in the comments with hackattack, the money is the correct data when I don't save but the moveSpdUpgrade array is modified either way.

I think you are running into a bit confusing thing about arrays.
What is happening never saves any data by another function or has something to do with the rest of your code.
Simple the method how you try to copy the array of that Sharedobject doesnt create two seperate Obejcts. Instead you are always working live on the sharedObject-array.
package
{
import flash.display.Sprite;
public class arraytester extends Sprite
{
private var a:Array = new Array(1,2,3,4,5);
private var b:Array = new Array("a","b","c","d","e","f");
public function arraytester()
{
// Both arrays are different Objects
trace(a); // 1,2,3,4,5
trace (b); //a,b,c,d,e,f
// Both arrays are pointing to the same Object
a= b;
trace(a); //a,b,c,d,e,f
trace (b); //a,b,c,d,e,f
b[1] = 2;
trace(a); //a,2,c,d,e,f
trace (b); //a,2,c,d,e,f
// a is a copy of b while becoming a seperate Object
a = b.concat();
b[0]= 1;
trace(a); //a,2,c,d,e,f
trace (b); //1,2,c,d,e,f
}
}
}

What is in the sharedObject that is loaded into memory and what is saved to disc are separate things. You are tracing the sharedObject in memory. Until you flush this sharedObject it probably wont save its image to disc. Try creating a new SharedObject and tracing that, it should be different.
Edit:
I see an error in what i told you to do before (below in the comments). I told you to make a new instance of moveSpdUpgrade to place in your shared object with the .concat method. The reason this doesnt work is because moveSpdUpgrade is a 2d array, i missed this detail. So calling .concat creates a new instance, but the new instance is still filled with references to arrays and it those arrays that you are editing. So to solve this we have to do a deep copy of moveSpdUpgrade. Here is a function that will accomplish that
function array2DConcat(target : Array) : Array {
var buff : Array = new Array(target.length);
for(var i : int = 0;i < target.length;i++) }
buff[i] = target[i].concat();
}
return buff;
}
and then if you change your method to
public function saveGame(){
parentMC.sharedObject.data.money = parentMC.money;
parentMC.sharedObject.data.moveSpdUpgrade = array2DConcat(parentMC.upgrades.tempMoveSpdUpgrade);
parentMC.sharedObject.flush();
}
hopefully that will work.

Related

save load error 1010 array objects with sharedObjects as3

i cant figure out this one so maby you guys can help me out.
i store some data in the form of a array filled with Objects in this example cards.
in my main class i have the following code:
deckSprite.savedData = SharedObject.getLocal("cardsdata");
deckSprite.savedData.data.savedArray = deckSprite.deckArr;
deckSprite.savedData.flush();
trace(deckSprite.savedData.data.savedArray);
the trace will output something like [object card1, object card2, object card3]
now in a static class called "deckSprite" i have this:
savedData = sharedObject.getLocal("cardsdata");
if (savedData.data.savedArray == undefined)
{
trace("no save yet");
}
{
else
{
trace("save loaded");
deckArr = savedData.data.savedArray;
trace(savedData.data.savedArray);
now my trace data turns out only ", ," (somehow the cards are gone).
now after i got saved data i restart my application and whenever he tryes to acces the deckArr it crashes giving me the error "A term is undefined and has no properties".
how is it possible that when i save the array it saves all the cards inside the array and when i restart the application its suddenly only ",,"but the cards are gone?
When serializing objects in AS3, you have to register their class using registerClassAlias() from package flash.net. So you have to call something like
registerClassAlias('com.example.deck', Deck)
in the program before any saving or loading happens.
See full reference at AS3 API Reference
NOTE: As pointed out by #BadFeelingAboutThis in comments, you have to register all referenced class in your Deck, i.e. if your deck looks like this:
class Deck {
var firstCard:Card;
var type:DeckType;
}
to be able to save Deck to SharedObject you have to call
registerClassAlias('com.example.deck', Deck);
registerClassAlias('com.example.card', Card);
registerClassAlias('com.example.decktype', DeckType);
before any saving/loading is done.
EDIT
Everything depends on content of your array
If I assume, your deckSprite is declared like this:
var deck1:Deck = new Deck();
var deck2:Deck = new Deck();
var deckArr:Array = new Array(deck1, deck2);
var deckSprite:DeckSprite = new DeckSprite()
deckSprite.setDeckArr(deckArr);
then before adding deckArray to SharedObject, you have to call registerClassAlias(). Sou your save code will look like this:
registerClassAlias('com.example.deck', Deck);
deckSprite.savedData = SharedObject.getLocal("cardsdata");
deckSprite.savedData.data.savedArray = deckSprite.deckArr;
deckSprite.savedData.flush();
trace(deckSprite.savedData.data.savedArray);
(replace the Deck with actual class you use for representing your decks)
Similarly the first line has to be called before you do any loading.
Of course it is best not to repeat yourself, so you should call registerClassAlias('com.example.deck', Deck); only once in your program, so for example in some init() method in your main class, if you have something like that.

Actionscript SharedObject data go randomly missing

I'm designing a game with save and load functions. Using the SharedObject technique I'm successfully saving most of the variables. However, there is this one Dictionary that sometimes ends up as "undefined". This happends perhaps 1/3 of the times i load the game.
This is my save function. It runs approximately every 2. second. I've removed a lot of code lines since they aren't relevant (saving the other variables). The trace line is for debugging purposes. Every time, also when the above mentioned error accurs, this line works. Consequently the dictionary isn't "undefined" at this moment.
private function saveGame():void
{
so = SharedObject.getLocal("progress", "/");
so.data.saved = true;
so.data.airportDict = airportDict;
trace(dayCount, so.data.airportDict["Australia"]);
so.flush();
}
The following lines run every time you open the program. The purpose is to decide whether there is a saved file to load or not.
so = SharedObject.getLocal("progress", "/");
if (so.data.saved == true)
{
loadProgress();
}
else
{
airportDict = new Dictionary();
resetAirportDict(); // This function just add lots of data to the dictionary.
}
And finally, the loading function:
private function loadProgress():void
{
so = SharedObject.getLocal("progress", "/");
airportDict = so.data.airportDict;
trace("Successfull start? " + airportDict);
}
As already mentioned, the airport dictionary's value is "undefined" maybe 1/3 of the time I run the program. For no appearant reason. This is a mystery.
SharedObject can store primitive types + Array and Object types. For other complex types you have to register the classes you wish to store using registerClassAlias(). In your cases Dictionary is a complex type that is not handled by default by SharedObject + the complex objects you might use as keys will have to be registered as well. So any complex class you use has to be register or else SharedObject will fail.
registerClassAlias("YourClassName", YourClassName);
This piece of code produce error because SharedObject doesn't understand complex objects:
var shareddata:SharedObject = SharedObject.getLocal("mydata")
var instance:MyClass;
if(shareddata.data["instance"] == undefined)
{
instance = new MyClass();
shareddata.data["instance"] = instance;
}
else
{
instance = shareddata.data["instance"];
}
But you can easily fix it by registering your class:
import flash.net.registerClassAlias;
registerClassAlias("MyClass", MyClass);
var shareddata:SharedObject = SharedObject.getLocal("mydata")
var instance:MyClass;
if(shareddata.data["instance"] == undefined)
{
instance = new MyClass();
shareddata.data["instance"] = instance;
}
else
{
instance = shareddata.data["instance"];
}
//no error and you truly get back your custom class instance the second time around.

Save Application state on Disk or some where so user access it later

In flex builder 4.5 i'm working on a project like cacoo.
I want to save diagrams(display object,ui components,text) before close the application into somewhere than I would be able to access after the application open again.
more clear:-If user edit some uml diagram on this project and save it for edit later and close application.after some days he/she want to edit previously saved diagram.
now how i'm save this diagram for future edit.
If save/open dialog will work for you, you can yse FileReference API. Before doing this, you have to implement serialization/deserialization of your state into/from String/ByteArray/XML object.
private var fileReference:FileReference;
// due to security restrictions, this method must be called from an
// event handler that responds to a user event (mouse click or key
// press), otherwise it will fail.
private function saveState(serializedState:*, fileName:String):void {
fileReference = new FileReference();
fileReference.addEventListener(Event.COMPLETE, onSaved);
fileReference.addEventListener(IOErrorEvent.IO_ERROR, onSavingError);
try {
fileReference.save(serializedState, fileName); // will open save dialog
} catch (e:Error) {
trace("error saving data: " + e.toString());
freeListeners();
}
}
private function onSaved(e:Event):void {
trace("saved!");
freeListeners();
}
private function onSavingError(e:ErrorEvent):void {
trace("error saving data: " + e.toString());
freeListeners();
}
private function freeListeners():void {
fileReference.removeEventListener(Event.COMPLETE, onSaved);
fileReference.removeEventListener(IOErrorEvent.IO_ERROR, onSavingError);
}
Similarly with restoring the state (use FileReference.browse(), then FileReference.load()).
If you need to save/restore app state without any dialogs, then you should probably use AIR (or SharedObject, as Raja Jaganathan suggested). But it seems to be not the case, as you want the user to be able to re-open the diagram in another system. To achieve this, you should allow the user to save his work to the appropriate place, so later he can move it to another machine/system and re-open it with your application.
Another alternative is to store everything on the server and provide the user with a list of saved files (like Cacoo does). If you go this way, you'll have to implement the corresponding server-side API. It may be REST API or smth like RTMP server. In the case of REST API, use FileReference.upload() to upload the data to your server, and URLLoader.load() to obtain it back.
You can store your diagram state through SharedObject for better you create one class which hold all of your state of Diagram so that later you can use
SharedObject using http://livedocs.adobe.com/flex/3/html/help.html?content=lsos_5.html
you can use registerClassAlias for custom class stored in sharedobject.
myClassInstance = new MyClass();
myClassInstance.x = 100;
myClassInstance.y = 100;
myClassInstance.text = "diagrams";
registerClassAlias("com.path.to.MyClass", MyClass);
myStuff = SharedObject.getLocal("myAppStuff");
myStuff.data.whatINamedIt = myClassInstance;
myStuff.flush();
now when get it back out... you can say:
myStuff = SharedObject.getLocal("myAppStuff");
var mySavedClass:MyClass = myStuff.data.whatINamedIt as MyClass;
Read mySavedClass instance value then inject to your diagram model when open again.
To implement application close event
http://www.flexer.info/2007/10/25/fabridge-warn-on-flex-application-exit/
Sprite or MovieClip other DisplayObject objects can not be direct serialized. So you should stored objects information (origin x,y, width, height, color, child info...). using a ByteArray or Array or Dictionary ... and that save to ShareObjects. later roll back from ShareObject and re-create Original Object. MovieClip or Sprite appropriate purpose is container.
Here is my test code.
1. create a Movieclip. purpose is container.
2. draw a rectangle using a graphics. And set the coordinates.
var drawWidth:Number = 500;
var drawHeight:Number = 300;
var rect:MovieClip = new MyRect();
rect.graphics.beginFill(0xffffff*Math.random(),1);
rect.graphics.drawRect(0,0,drawWidth,drawHeight);
rect.graphics.endFill();
rect.x= 300;
rect.y= 100;
3. Stores the information in the array.
var myRectInformation:Array = new Array();
myRectInformation.push(rect.x);
myRectInformation.push(rect.y);
myRectInformation.push(drawWidth);
myRectInformation.push(drawHeight);
var bmd:BitmapData = new BitmapData(rect.width, rect.height,true,0);
bmd.draw(rect);
//is byteArray.
myRectInformation.push(bmd.getPixels(new Rectangle(0,0,bmd.width,bmd.height)));
4. save to SharedObjects, array.
var mySaveData:SharedObject = SharedObject.getLocal("myStorage")
mySaveData.data.myRectInformation = myRectInformation;
mySaveData.flush();
5. this is load from SharedObject data stored. and recreate Objects.
var rect:MovieClip = new MyRect();
var loadBmd:BitmapData = new BitmapData(mySaveData.data.myRectInformation[2], mySaveData.data.myRectInformation[3], true, 1);
loadBmd.setPixels(new Rectangle(0,0,loadBmd.width,loadBmd.height), mySaveData.data.myRectInformation[4]);
var bmp:Bitmap = new Bitmap(loadBmd);
rect.addChild(bmp);
rect.x = mySaveData.data.myRectInformation[0];
rect.y = mySaveData.data.myRectInformation[1];
addChild(rect);

How to duplicate loaded *.swf without setting a class name

I have read this article about abstracting assets from ActionScript:
Abstracting Assets from Actionscript in AS3.0 – Asset Libraries and DuplicateMovieClip
But it requires to set the Linkage Class name. How can I get the same result without setting the linkage class name?
What I want to do is to cache a loaded asset, and use the cached version every time I request the same URL. A solution is to clone the loaded DisplayObject, but I think it's unnecessary since I only want a new copy.
I think the way to do that is to use byte arrays
here's a quick sample
// once you load your data...
private function loaderComplete(event:Event):void
{
var loaderInfo:LoaderInfo = LoaderInfo(event.target);
var byteArray:ByteArray = loaderInfo.bytes; //<- this will create your byte array
}
you can then use byteArray.readObject(); to generate the new class;
look at senocular's post at http://www.kirupa.com/forum/showthread.php?p=1897368
where he's got a function like this:
function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
//that you use with
newObjectCopy = clone(originalObject);
hope this gets you started
As of Flash 11.3, there's a function named getQualifiedDefinitionNames that tells me exactly what linkage names should I use with getDefinition, so there's no need to know the values beforehand.

Actionscript - Variable Assignment without reference?

Should be easy. I have an object. I want to modify it, but before i do I want to save a copy of it that I can go back to. I tried setting copy = original but when i modify the attributes of the original the copy also shows the changes. I am assuming this is because in actionscript any time you assign, it really just stores a reference to the original object. So whats the best way for me to store a copy of the original object for later use?
var newObj:Object = Object(ObjectUtil.copy(oldObj));
"Copies the specified Object and returns a reference to the copy. The copy is made using a native serialization technique. This means that custom serialization will be respected during the copy.
This method is designed for copying data objects, such as elements of a collection. It is not intended for copying a UIComponent object, such as a TextInput control. If you want to create copies of specific UIComponent objects, you can create a subclass of the component and implement a clone() method, or other method to perform the copy."
http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#copy()
What you are looking for is a deep copy of the object rather then passing by reference. I found the answer here which uses the new ByteArray class in AS3:
http://www.kirupa.com/forum/showthread.php?p=1897368
function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
Which you then use like this:
newObjectCopy = clone(originalObject);
Cheers!
// duplicate any given Object (not MCs)
Object.prototype.copy = function()
{
ASSetPropFlags(Object.prototype,["copy"],1);
var _t = new this.__proto__.constructor(this) //
for(var i in this){
_t[i] = this[i].copy()
}
return _t
};
Usage
x = ["1","2","3",[4,5],[{a:1,b:2}]]
y = x.copy()
y[0] = 0
y[3][0]="d"
trace(x)
trace(y)