Building an Address Book > Storing Data Locally

 

Storing Data Locally

Macromedia Flash MX allows you to store information on a user's computer much like information is stored by a browser with a cookie. The mechanism for local data storage is a built-in object, called a "SharedObject". Properties assigned to a SharedObject are saved to the user's hard disk when a movie quits or when a specific write command is issued.

Although we'll cover the basics of reading from and writing to a SharedObject, much more information is available under the SharedObject entry in the ActionScript Dictionary (Help > ActionScript Dictionary).

To encapsulate the work of storing local data, we'll use two classes: Contact and ContactManager. The Contact class acts as a simple custom data type; it lets us store a contact's information (first name, last name, phone number, etc) as the properties of an object. The ContactManager class handles reading from and writing to our application's SharedObject.

Before we examine the Contact and ContactManager classes in detail, let's consider the simplest way to create, write to, and read from a SharedObject.

The following statement asks Flash to provide a local SharedObject named "myInfo". If a SharedObject by that name exists, Flash returns it; if not Flash creates a new SharedObject by that name. In either case, we store the returned SharedObject in the variable so.

  // Create or retrieve a SharedObject named "myInfo".
  so = SharedObject.getLocal("myInfo");

Notice that SharedObjects aren't constructed, they are returned by getLocal(). Now we add a property to our SharedObject to remember a favorite color:

  so.data.favoriteColor = "orange";

The favoriteColor property must be defined on the special data property, which contains all the data that will be saved to disk. Assigning our new property does not cause Flash to write the information to disk. Data is automatically written to disk when the movie is unloaded from the Flash Player or when no more references to the SharedObject exist. If desired, we can also "flush" the object, forcing a write to disk operation:

  so.flush();

This comes in handy when we want to ask the user for more disk space, or when we're explicitly synching a SharedObject between two movies.

Now that we've created a SharedObject, we read its properties just like we would any object's:

  trace(so.data.favoriteColor);  // Displays: orange

If the movie is closed and then reopened later, we first retrieve the SharedObject before reading its properties:

  // Create or retrieve a SharedObject named "myInfo".
  so = SharedObject.getLocal("myInfo");
    
  // Now read its favoriteColor property.
  trace(so.data.favoriteColor);  // Displays: orange  

Next we'll put these concepts to use in our address book application.