NSExplorer
NSExplorer

Reputation: 12149

Memory leak in using NSDictionary of NSDictionaries

I am trying to parse XML. I basically have an NSMutableDictionary (say root) the elements of which are other dictionaries (say branch_1, branch_2, branch_3, etc).

While parsing XML, for each branch, I'm creating an NSMutableDictionary and adding elements to it this way:

if ([elementName compare:@"branch_1"] == NSOrderedSame) 
{
    [root setObject:[[NSMutableDictionary alloc] init] forKey:@"branch_1"]; //Creating a new NSMutableDictionary            
} 

//Adding elements to the newly created NSMutabeDictionary 

if ([elementName compare:@"element_1"] == NSOrderedSame) 
{
   [[root objectForKey:@"branch_1"] setObject:someObject forKey:@"element_1"];                                      
} 

if ([elementName compare:@"element_2"] == NSOrderedSame) 
{
   [[root objectForKey:@"branch_1"] setObject:someObject forKey:@"element_2"];                                      
}

I then finally release my root dictionary in the dealloc method. However the analyze tool in Xcode shows a leak in the line where I've created new dictionaries for branch_1 etc.

I'm guessing I should release the branch dictionaries before I release the root dictionary. However shouldn't the contents of the root dictionary be freed on releasing the root itself ?

Please let me know how I can fix this leak. Any help will be appreciated !!

Upvotes: 0

Views: 1010

Answers (1)

Dirk
Dirk

Reputation: 31053

The problem is, that you don't release the references to the newly created dictionary. In

[root setObject:[[NSMutableDictionary alloc] init] forKey:@"branch_1"];

you create a new dictionary by virtue of

[[NSMutableDictionary alloc] init]

Your root dictionary will retain that value. The original reference, for which you are responsible because you used alloc to obtain it, is leaked here. So, try

[[[NSMutableDictionary alloc] init] autorelease]

instead.

Edit Another way to achieve the desired behaviour would be to use one of the convenience constructor methods defined by class NSMutableDictionary:

[NSMutableDictionary dictionary]

The object will be kept alive as long as someone has a (properly retained) reference to it. In this case, your root dictionary will hold onto the newly created child dictionary (setObject:forKey: sends the retain message to the values).

Upvotes: 4

Related Questions