Creating weak references in Actionscript 3
15th August 2007
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.
Tags: Actionscript, Free code, Weak reference

2 Comments add your own
Hi Richard,
I wanted to let you know that I made mention of this post in an article on weak references on my blog. Check it out here:
http://mimswright.com/blog/?p=213
Thanks
Mims H. Wright | 10th December 2007 at 00:01
[...] kann, allerdings nur unter schweren Performance Einbussen. Glücklicherweise gibt es einen Workaround, um trotzdem eine schwache Referenz halten zu [...]
OOP Best Practices: Delegation - blog.ch | 13th February 2012 at 13:46
Leave a Comment comment policy
XHTML: you can use these tags - <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>Subscribe to the comments via RSS Feed