4thSpace
4thSpace

Reputation: 44332

How to clear a dictionary?

I'm currently doing the following to clear out an NSMutableDictionary

[myDictionary release];
myDictionary = [[NSMutableDictionary alloc] init];

The release line doesn't actually release any objects in the dictionary. I can still see all of them on the next line. It isn't until the alloc line is executed that the dictionary is zeroed out. Is there a better way to do it?

Upvotes: 19

Views: 28895

Answers (4)

Dan
Dan

Reputation: 1739

[aMutableDictionary removeAllObjects];

from Apple's documentation:

(void)removeAllObjects

Description - Empties the dictionary of its entries. Each key and corresponding value object is sent a release message.

Availability - iOS (2.0 and later)

Upvotes: 3

bbum
bbum

Reputation: 162712

You say:

The release line doesn't actually release any objects in the dictionary. I can still see all of them on the next line. It isn't until the alloc line is executed that the dictionary is zeroed out. Is there a better way to do it?

If -release of the mutable dictionary causes the dictionary to be deallocated -- drops the retain count to zero -- then the mutable dictionary will release all contained objects. Always.

Thus, if the objects aren't being released, then this suggested "fix"...

[myDictionary removeAllObjects];
[myDictionary release];
myDictionary = [[NSMutableDictionary alloc] init];

... is a memory leak in that the original instance of NSMutableDictionary will be leaked.

As a result, calling -removeAllObjects will empty the dictionary and release all of the contained objects, but you still have a memory leak that you should figure out and fix.


To be blunt:

If the objects in your dictionary are not being deallocated when the dictionary receives the above -release (without calling -removeAllObjects), then there is a memory leak. It is either:

  1. The objects in the dictionary have been retained an extra time.

  2. There is still an outstanding -retain on the dictionary.

Since you say the objects are being correctly (as in, as expected) deallocated when you call -removeAllObjects, then it must be (2). Look through your code and figure out where there is an extra -retain of the dictionary. You can use the Object Alloc instrument to figure out exactly where all of the retains come from.

Upvotes: 30

Ben Gottlieb
Ben Gottlieb

Reputation: 85532

-removeAllObjects will work, as Andy mentioned. However, if any of your dictionary's objects are auto-released, or if the dictionary itself has been autoreleased somewhere along the line, then they won't be dealloc'd until the next time the runloop finishes (when the autorelease pool is drained).

Upvotes: 6

Related Questions