Creating weak references in Actionscript 3
Posted on
A weak reference is a reference that does not prevent the object from being garbage collected. 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 on my public GitHub repository.
To use the class
// Create a weak reference var weak:Weakref = new WeakRef( obj ); // Later use the referenced object var strong = weak.get(); if( strong != null ) { // use strong here } else { // garbage collector has disposed of the object }
If the get method returns null then the object has been garbage collected.
The source is free under the terms of the MIT licence.
Share this post or a comment online -
Also in the collection Actionscript
- Finite State Machines for AI in Actionscript
- Singletons - we're better off without them
- Simple example of acceleration
- List Loader for Actionscript 2
- Singleton Factory
- Events in Actionscript 2
- Different types of weak references
- Events in Actionscript 3
- Polling the keyboard in Actionscript 3
- Radial Perlin Noise
- The parentheses operator
- Object Pool class
- The I in Interface
- Four ways to link a list (a performance test on linked list architectures)