Steve Kuo
Steve Kuo

Reputation: 63104

Clear a Flex ActionScript Dictionary

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

Upvotes: 13

Views: 9692

Answers (6)

Rizwan_Mohammed
Rizwan_Mohammed

Reputation: 313

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.

Upvotes: 0

dscfgos
dscfgos

Reputation: 11

Just:

dictionary = new Dictionary()

Upvotes: 0

greglieb
greglieb

Reputation: 64

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.

Upvotes: 2

Herms
Herms

Reputation: 38838

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

Upvotes: 6

David Dumke
David Dumke

Reputation: 13

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

Upvotes: 1

Jason
Jason

Reputation: 2503

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

Upvotes: 6

Related Questions