开发者

Understanding Memory management with NSDictionary release

iOS memory management is still something weird to understand to me but that's the most interesting aspect to me also, so I'm asking for some help here with my code.

I try to instantiate a NSDictionary object, I use it then I'd like to release but I got an object released error, this is the code:

if ([jsonArray count] > 0) {        
    NSDictionary *commentDictionary = [[NSDictionary alloc]init];
    int i;
    for (i = 0; i < [jsonArray count]; i++) {
        commentDictionary = [jsonArray objectAtIndex:i];
        NSLog(@"debugging message here"]);
        commentLabel.text = [commentDictionary objectForKey:@"commentText"];
        //[commentDictionary retain];
    }
    //[commentDictionary release];
    commentDictionary = nil;
    NSLog(@"NSDictionary retainCount = %d",[commentDictionary retainCount]);
}

Nothing special, I fill a dictionary from an array, in my code you can see I tried to release but than I commen开发者_运维百科ted out because of the error. Why I can't release the dictionary?

Besides what's the difference between setting NSDictionary to nil that returns zero in retainCount and release (that should make the count -1)?

I thank you very much in advance for any kind of help in this topic.

Fabrizio


Do not call retainCount

retainCount is a horrible method to use for trying to figure out memory management. The absolute retain count of an object is rarely interesting and often will be unfathomable due to implementation details.

Read the documentation. It is pretty straightforward.

Now, to your code.

  • the alloc/init assignment to commentDictionary in your first line isn't needed and that object will be leaked on the assignment that is the first line in the for() loop.

  • instead of using for(;;), you could use for(commentDictionary in jsonArray) {...}

  • there is no reason to retain or release commentDictionary in that code; the object retrieved from the array will remain valid throughout the scope of that method.

  • Objective-C is a "nil eats messages" language. When you call a method on nil, that call will return 0 in almost all cases.


Oh, and what Cyril said. The static analyzer is a wonderful tool!


I advise you to run the static analyzer on that code: a lot of the mistakes that I do regarding memory management are explained by following the steps that the little blue arrows describe.

That's a very useful/cool/forgiving tool to discover your own mistakes and understand what's happening. Build and Analyze in the build menu.

PS: retainCount is often wrong;

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜