Local SharedObject


This is a simple and convenient approach to saving small amounts of data on your device (100 KB maximum). You don’t need to manage where the data is saved and if it already exists—this is handled automatically for you.

The SharedObject static class belongs to the flash.net package and inherits from Even tDispatcher.

A Flash shared object is similar to a browser cookie, but it does not expire and it has a default size limit of 100 KB. The object is written in the proprietary ActionScript Message Format (AMF). You can store data types such as String, Array, XML, Number, Data, Object, and ByteArray. An application can only access its own SharedObject data. A single application can have multiple shared objects.

To use this approach, first get a reference to your application’s shared object. The getLocal() method creates it if it does not already exist:

import flash.net.SharedObject;
var so:SharedObject = SharedObject.getLocal(“myApplication”);

The preceding code creates a new directory in the application storage area and a shared object inside it called myApplication.sol.

To add data to a shared object, add attributes to its data (the data object itself is readonly). Here we are storing a string, an array, a boolean, and an object:

so.data.animal = “Hamster”;
so.data.food = [“Grains”, “Avocado”, “Carrot”];
so.data.isVegetarian = true;
so.data.stuff = {toy:”Wheel”, house:”Cage”};

To save these new attributes to the persistent local file, call the flush method. For devices, it is recommended that you save data right away to avoid losing the data if the application is terminated. Saving data can be performance-intensive, so carefully plan when your application initiates a save:


If you wish to monitor the save process, create a String variable to store what the flush method returns. If the result is pending, set a listener to trace the reason the data was not stored:

import flash.net.SharedObjectFlushStatus;
import flash.events.NetStatusEvent;
var flushStatus:String = so.flush();
if (flushStatus != null) {
switch(flushStatus) {
case SharedObjectFlushStatus.PENDING:
case SharedObjectFlushStatus.FLUSHED:
function onFlushStatus(event:NetStatusEvent):void {
To check that an attribute exists, do the following:
if (so.data.animal == undefined) {
trace(“What are you?”);
} else {
trace(“Hello again, “, so.data.animal);
To display all the attributes, use:
for (var i:String in so.data) {
trace(“prop”, i, “: “, so.data[i]);
// prop food : Grains,Avocado,Carrot
// prop isVegetarian : true
// prop stuff : [object, Object]
// prop animal : Hamster
To check the size of the shared object, use:
// 140

If you wish to remove an attribute, use the delete command. Setting the variable to undefined or null changes its value but doesn’t remove it:

delete so.data.animal;

If you wish to remove all of the attributes, use the clear() method. This method will also delete the shared object itself: