0

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 !!

NSExplorer
  • 11,849
  • 12
  • 49
  • 62

1 Answers1

4

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).

Community
  • 1
  • 1
Dirk
  • 30,623
  • 8
  • 82
  • 102
  • …or `[NSMutableDictionary dictionary]`. – zoul Jan 17 '11 at 15:29
  • @zoul: ... which would actually be shorter. Thanks. Will edit my answer. – Dirk Jan 17 '11 at 15:32
  • On doing this, will the objects not be released prematurely? I want the objects (represented by "someObject" in my code) to to stick around throughout the duration of the application. – NSExplorer Jan 17 '11 at 15:32