Is it possible to clear a Flex flash.utils.Dictionary
? I have a Dictionary
that I want to clear (remove all elements).
6 Answers
I think this will work, but I'm not 100% sure, as you're modifying the dictionary while iterating over it:
function clear(d:Dictionary):void {
for(var id:* in d) {
delete d[id];
}
}
However, I generally just create a new Dictionary whenever I need to clear one (though if it's referenced in multiple places then that might not work for you).
To remove all the elements in the Dictionary, loop through each key and use the delete keyword
function clear(dict:Dictionary):void
{
for(var key:Object in dict)
{
delete dict[key];
}
}
If you want to be 100% sure that your deleted keys are garbage collected, you must replace your Dictionary instance with a new Dictionary.
dict = new Dictionary();
I once had a Dictionary object with 3 million Strings as keys. Those Strings would only be garbage collected when the Dictionary instance itself was.
Not only do you need to make sure the key is of type object or * you need to get the keys first then delete them from the dictionary. Otherwise you will end up one key left in the dictionary(the last one).
I remember the above code working before but recently that has changed with the last iteration of flash player.
This code will ensure they are all removed including the last one.
//Clean up the dictionary
var keys:Array = [];
var key:*;
for ( var key:* in dictionary )
keys.push( key );
for each ( var key:* in keys )
delete dictionary[ key ];