« Events in Actionscript 2 | Different types of weak references »

Creating weak references in Actionscript 3

15th August 2007

It’s great that Actionscript 3 has weak references in the EventDispatcher and Dictionary classes. But sometimes you want to create your own weak references. Something along the lines of

var weak:WeakRef = new WeakRef( someObject );

Well, there is a way. It’s a bit of a hack, and unfortunately uses a full Dictionary object for each weak reference, but it works. The source code is very short:

package
{
    import flash.utils.Dictionary;
	
    class WeakRef {
        private var dic:Dictionary;
		
        public function WeakRef( obj:* ) {
            dic = new Dictionary( true );
            dic[obj] = 1;
        }
		
        public function get():* {
            for( var item:* in dic ) {
                return item;
            }
            return null;
        }
    }
}

Download source code Download the WeakRef class.

To use it

// Create a weak reference
var weak:Weakref = new WeakRef( obj );

// Use the referenced object
var strong = weak.get();
if( strong != null ) {
    // use strong here
} else {
    // garbage collector has disposed of the object
}

The source is free under the terms of the MIT licence. Please download the source file rather than copying and pasting since it contains the licence notice and useful comments.

Read more articles about Actionscript 3 

1 Comment

Comments closed.