Previous Page
Next Page

Recipe 17.5. Removing Data from a Shared Object

Problem

You want to remove properties from a shared object, or you want to remove the entire shared object from the disk.

Solution

Use delete to delete a property from the shared object's data property, or use the clear( ) method to remove the shared object.

Discussion

Removing data from a shared object is a straightforward process, but it has to be done the correct way. In ActionScript you will commonly find that people set complex variables such as objects or arrays to null or undefined to remove them. Doing this with a shared object, however, is the wrong approach.

// Attempt to delete someVariable from the example shared object.
// This statement will compile but does not do as we intend it to.
example.data.someVariable = null;

A shared object is capable of storing both null and undefined as valid values. Therefore, the preceding code does not remove someVariable from the data property, but rather someVariable is given the value of null in the assignment statement instead of being removed from the shared object. The correct way to completely remove something from a shared object is to delete it, like this.

// Remove someVariable from the example shared object.
delete example.data.someVariable;

You can also remove an entire shared object by invoking the clear( ) method on it. After the clear( ) method is called, the physical .sol file that stores the shared object is removed form the disk. The following code is an example of removing a shared object.

// Create a shared object and store some data in it
var example:SharedObject = SharedObject.getLocal( "example" );
example.data.someData = "a value";

// Displays: a value
trace( example.data.someData );

// Remove the shared object from the disk
example.clear(  );

// Displays: undefined
trace( example.data.someData );

After a shared object has been cleared, the shared object reference is still valid. This means that you can use the shared object as if it were newly created. Adding values to the data property makes them persistent, as you would expect with normal shared object behavior. In effect, the clear( ) method empties the shared object entirely, making it ready to be used again if needed.


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)