asdg>> technotes>> save data to disk

Version: Flash Player: v6, Flash Authoring: MX 2004
Date Added: April 21, 2004

Flash Player 6 introduced a class called SharedObject that can store ActionScript data to the end-user's hard drive (much like a JavaScript cookie). However, the SharedObject class is notoriously awkward to work with (partly because it is also used to store data remotely via Macromedia's Flash Communication Server). To ease the pain of storing data locally, you can use my custom LocalData class, which wraps the funtionality of the SharedObject class into two easy-to-use methods: save() and load().

The following code uses LocalData.save() to store the value "Colin" in the field username of the general record userDetails:

LocalData.save("userDetails", "username", "Colin");

The following code retrieves the value "Colin" from the field username of the general record userDetails. It stores the retrieved value in a local variable named uname:

var uname:Object = LocalData.load("userDetails", "username");

Here's a demonstration of the LocalData class in action. Note that the "Save" button saves the data to your local hard disk. You can load that data even after leaving and returning to this page.

>> Download the LocalData class and example

Here's the source code for the LocalData class:


/**
 * A class for storing typed data locally. Wraps the SharedObject
 * class, offering more intuitive access to its functionality.
 */ 
class LocalData {

  /**
   * Private constructor prevents the instantiation of this class.
   */
  private function LocalData () {
  }

  /**
   * Saves a value to disk using a SharedObject instance.
   *
   * @param   record   The name of the record to retrieve.
   * @param   field    The specific field to retrieve within 
   *                   the specified record.
   * @value   value    The new value for the specified field.
   */
  public static function save(record:String, field:String, value:Object):Void {
    var so:Object = Object(SharedObject.getLocal(record));
    so.data[field] = value;
    so.flush();
  }

  /**
   * Retrieves a value from disk using a SharedObject instance.
   *
   * @param   record   The name of the record to retrieve.
   * @param   field    The specific field to retrieve within 
   *                   the specified record.
   * @return  The value of the specified field.
   */
  public static function load (record:String, field:String):Object {
    return Object(SharedObject.getLocal(record)).data[field];
  }
}

The LocalData class is part of the Unity core client class library. For complete documentation see the LocalData entry in the Unity core documentation.

>> Read LocalData documentation