Iphone – NSDictionary leak on iPhone and object reference graph


I am simply loading a plist into a temporary dictionary for initializing my data model. Unfortunately this single line of code below results in consistent leak throughout the app life cycle as per Instruments. The leaked objects being NSCFString and GeneralBlock on a Malloc and the responsible library being Foundations.

My two questions for the experienced eyes:

  1. Am I doing something strange to trigger this ? I tried surrounding it in autorelease block but it had no effect.
  2. Is there a way to print list of object references of a suspect object to get insight into the object orphaning process.

Leaking Line:

NSDictionary *tempDict = [NSDictionary dictionaryWithContentsOfFile:
                             [[NSBundle mainBundle]

totalChapters = [[tempDict objectForKey:@"NumberOfChapters"] intValue]; 
chapterList  = [[NSMutableArray alloc] initWithCapacity: totalChapters];
[chapterList addObjectsFromArray:[tempDict objectForKey:@"Chapters"]];

Best Solution

It appears you may be leaking at this line:

[[NSMutableArray alloc] initWithCapacity: totalChapters];

If that object isn't being released, then any objects you add to it won't be released either

Edit (because it's too long for a comment):

Instruments tells you where the memory was allocated, but not why it is still being retained. When NSDictionary loads the contents of a file, it has to create an object for each element it loads. If one later retrieves an object using objectForKey:, retain it and forget to release, a leak will be reported. The dictionaryWithContentsOfFile statement will be blamed for it because it performed the allocation.

I concur with Don's phantom debugging. Most likely you haven't released the old chapterList when you assign to it the second time.

Related Question