2 Replies Latest reply on Feb 6, 2007 12:12 PM by GlennZim

    Shared Object question

      I use shared objects a lot and I've run into a problem. When saving an array into a local shared object, if the array is changed, it automatically changes in the shared object when the swf is exited. For example:

      // ----- create a shared object ----- //
      var cSaved:SharedObject = SharedObject.getLocal("test","/");

      // ----- create an object, an array, and a numeric variable ----- //
      var anobject:Object = new Object();
      anobject.aname = "bob";
      var anarray:Array = new Array(0,1,2,3,4);
      var anum:Number = 100;

      // ----- save this info to the shared object ----- //
      cSaved.data.thisobject = anobject;
      cSaved.data.thisnum = anum;
      cSaved.data.thisarray = anarray;

      // ----- change the values of the variables ----- //
      anobject.aname = "willie";
      anum = 50;
      anarray[3] = 100;

      // ----- check the values in the shared object. They changed! ----- //


      In the above code, when I changed the value of anarray[3] to 100, it automatically changed the value of cSaved.data.thisarray. However, changing the value of anum does NOT change the value of cSaved.data.thisnum when exiting the swf.

      Is there a way to stop arrays saved in a shared object from updating like this? It does it with objects too. Thanks.


        • 1. Re: Shared Object question
          abeall Level 3
          There area a couple of different things that can make this confusing:

          First, there is a difference between creating a copy, and creating a reference. Specifically, Numbers, Strings, and Booleans are primitive values, so when you do this: myVar1 = myVar2, it basically copies the value of myVar2 into a new variable, named myVar1. However, complex data types, such as Arrays and generic Objects, do not copy the value, but rather create a reference. So when you do myArr1 = myArr2, you are just creating another reference named myArr1 to the same Array, which is referenced to by myArr2.

          Solution is to copy the array. There is not Array.clone() method, but you can effectively do it like this:
          myClonedArr = myArr.slice();

          Second, a SharedObject is automatically flushed when the client is closed. The only thing that SharedObject.flush() does for you is prompt the user for more disk space if the Player needs more than the default 100K.

          • 2. Re: Shared Object question
            GlennZim Level 1
            Thanks for the explanation. It doesn't make my life any easier, but it is good to know why the shared object does what it does!

            I did find a workaround for the array problem by first using .join("-") to group everything together into one string when saving, and then using .split("-") to break it back apart when retrieving. Saving objects, however, will be a little trickier.

            Thanks again,