开发者

resetting contents of NSMutableDictionary iVar

I have an ivar I'll call dictionaryIvar, which is a mutable dictionary. Occasionally, its contents must be erased and reset with new contents. The contents are added over several iterations of indefinite quantity, hence why it is mutable.

Is it enough to "reset" or release the dictionary with:

 self.dictionaryIvar=nil;

And then in a different method, where needed, recreate 开发者_运维知识库the dictionary with:

 if(!self.dictionaryIvar){
 self.dictionaryIvar = [NSMutableDictionary dictionary];
 }

Would this be acceptable, or would this leak the object?


If your property is defined like this:

@property (nonatomic, readwrite, retain) NSMutableDictionary *dictionaryIvar;
//...
@synthesize dictionaryIvar;

then the synthesized method would take care of releasing/retaining the dictionary objects.

self.dictionaryIvar = [NSMutableDictionary dictionary];

should thus be sufficient.

There's a distict difference between self.dictionaryIvar and dictionaryIvar wherein the former gets passed to a synthesized property method (- (NSMutableDictionary *)dictionaryIvar; and - (void)setDictionaryIvar:(NSMutableDictionary *)aDictionary; respectively) and dictionaryIvar simply accesses the variable.

Thus this would leak (and crash, both):

dictionaryIvar = [NSMutableDictionary dictionary];

while this wouldn't:

self.dictionaryIvar = [NSMutableDictionary dictionary];

But I'd (in most cases) really just go with this simple call:

[dictionaryIvar removeAllObjects];


Instead of doing that, why not just...

[dictionaryIvar removeAllObjects];


If you want to change the contents of the dictionary, you could just replace it with the new dictionary. In one line:

[dictionaryIvar setDictionary:[NSMutableDictionary dictionary]];

That has the same effect of doing a [dictionaryIvar removeAllObjects] (which also sends a release to all objects contained in it), followed by adding the objects from the new dictionary (in your case, empty).

Also, by doing this you don't have to worry about your ivar's ownership and memory management issues if all you need to do is 'reset' the dictionary...


Assuming that your @property is set to retain, that should be fine. Using the dot notation (self.dictionaryIvar) automatically will release and retain your dictionary.

If you're just trying to clear the dictionary, though, it might be better to just call the dictionary's -removeAllObjects method:

[self.dictionaryIvar removeAllObjects];


It's not leaked as you are setting it with nil using self., it will invoke the setter function for your dictionaryIvar and then will release the previously held object and assign nil.

I would prefer to call proper release on the dictionaryIvar variable.

  [dictionaryIvar release];
    dictionaryIvar = nil;

 if(!dictionaryIvar){
  dictionaryIvar = [[NSMutableDictionary dictionary] retain];
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜