Weak References with Dictionaries in Actionscript
Thursday, October 11th, 2007Actionscript dictionaries are a great tool for dealing with memory management because you can use them to create weak references to objects. This means that the object automatically goes away upon garbage collection if the only reference to it is in the Dictinary.
To use a dictionary in this manner, simply pass true to the constructor. However, one should note that this *only* makes the keys of the Dictionary weak.
For example:
class MyObject { public var message:String; } var dict:Dictionary = new Dictionary(true); var obj1:MyObject = new MyObject(); obj1.message = "My really long message..."; var obj2:MyObject = new MyObject(); obj2.message = "My second really long message..."; dict[obj1] = true; //obj1 is weakly referenced dict[2] = obj2; //obj2 is strongly referenced
If the only reference to an object is the *key* of a weakly referenced dictionary, the object will not persist after garbage collection. However, if the only reference to an object is the *value* of a key in a weakly referenced dictionary, the reference is considered strong and will force the object to persist after garbage collection.
So, what do you do if you want to store a dictionary of weakly referenced objects, but key them off of a meaningful value (such as an item id) rather than their reference id?
The answer is to use a simple WeakReference class ([source](http://www.bigroom.co.uk/blog/create-your-own-weak-references-in-actionscript-3)):
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; } }
From here, you can do the following:
var dict:Dictionary = new Dictionary(true); var obj1:MyObject = new MyObject(); obj1.message = "My really long message..."; var obj2:MyObject = new MyObject(); obj2.message = "My second really long message..."; dict[1] = new WeakReference(obj1); //weakly referenced value dict[2] = new WeakReference(obj2); //weakly referenced value
Now, you can key based off of a meaningful value, and still get all the benefits of weak references.