Different types of weak references
15th August 2007
Actionscript 3 seems to have two different types of weak references. The difference relates to method closures (or bound methods) and the weak references used by the EventDispatcher and Dictionary classes. Try the following
package
{
import flash.display.*;
import flash.utils.Dictionary;
import flash.events.MouseEvent;
public class Test extends Sprite
{
private var dic:Dictionary;
private var store:Function;
public function Test() {
var listen:Sprite = new Sprite();
listen.graphics.beginFill( 0xFF0000 );
listen.graphics.drawCircle( 50, 50, 50 );
addChild( listen );
dic = new Dictionary( true );
dic[inDictionary] = 1;
dic[inDictionaryAndProperty] = 1;
store = inDictionaryAndProperty;
listen.addEventListener( MouseEvent.CLICK, doClick );
listen.addEventListener( MouseEvent.CLICK,
inEventListeners, false, 0, true );
}
public function doClick( ev:MouseEvent ):void {
for( var fn:Object in dic ) {
fn( ev );
}
}
public function inDictionary( ev:MouseEvent ):void {
trace( "method in dictionary" );
}
public function inDictionaryAndProperty( ev:MouseEvent ):void {
trace( "method in dictionary and property" );
}
public function inEventListeners( ev:MouseEvent ):void {
trace( "method in event listeners" );
}
}
}
The output is
method in dictionary and property method in event listeners
The EventDispatcher retains the weak reference to the method closure (inEventListeners) because the object it’s bound to still exists. It will drop its reference to the method closure when the bound object no longer exists.
The Dictionary, however, doesn’t retain the weak reference to the method closure (inDictionary), despite the fact that the method still exists (it exists in the class) and the object it is bound to still exists.
If, however, you have another, strong, reference to the same method closure (inDictionaryAndProperty), then it isn’t garbage collected and the Dictionary retains its reference to it.
So the EventDispatcher and Dictionary treat weak references to method closures differently.
It seems to me that the Dictionary takes a purist view – it holds the only reference to the method closure so it can be garbage collected – while the EventDispatcher takes a practical view – the method and the bound object both exist so the method closure should be retained.
Why the difference? I’d love to know.
Tags: Actionscript, Free code, Weak reference
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