13
votes

Is it possible to clear a Flex flash.utils.Dictionary? I have a Dictionary that I want to clear (remove all elements).

6

6 Answers

6
votes

I don't believe there is an explicit clear command.

However, you could write your own that would loop through all the keys and run this

delete dict[key]; 

Or you can just reassign

dict = new  Dictionary()
6
votes

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).

2
votes

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.

1
votes

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 ];
0
votes

Just:

dictionary = new Dictionary()
0
votes
public static function clear(dict:Dictionary):void {
        var key:*
        for(key in dict) {
            delete dict[key];
        }
    }

Use the above function as a utility function and you can use it throughout your code base.