2007年5月21日星期一

Weak References

If you want a reference to exist for an object that will not be counted towards the reference count used by the Garbage collector, then you can use a weak reference. Weak references are ignored by the reference counter and can exist even if the object is deleted.

You can't use weak references anywhere, however. There are only two places you can use weak references in ActionScript 3. One place is with Dictionary objects. The Dictionary constructor allows one optional parameter that specifies whether or not keys within the instance are weak references or not. False is the default value which means strong references. If you pass true, the Dictionary instance will use weak references

ActionScript Code:

var dict:Dictionary = new Dictionary(true); // use weak references as keys


If you do this for Dictionary instances, the keys you use to store values will not be counted towards that object's reference count.

ActionScript Code:

var obj:Object = new Object();
dict[obj] = true;
delete obj; // obj can be garbage collected since the dict reference isnt counted



The EventDispatcher's addEventListener is the other place you can specify weak references. addEventListener has a parameter that lets you specify the listener reference as being weak (since listeners internally require a reference to the object they are listening to).

ActionScript Code:

// addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
addEventListener(MouseEvent.
CLICK, clickHandler, false, 0 true); // use weak references


For addEventListener, the default is also false, using strong references, though it's good habit to use weak listeners to help with garbage collection.

0 评论: