Reputation: 44332
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
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
Reputation: 88365
I can't test it at the moment, but have you tried the removeAllObjects
method of NSMutableDictionary
?
Upvotes: 34
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:
The objects in the dictionary have been retained an extra time.
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
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