James White
James White

Reputation: 784

Memory management with NSDictionary

I found an answer to this a while ago, and made a mental note to fix it, but now I can't for the life of me find the post again.

Very simple - my current method for adding dictionaries to an array is leaky. Please, what is the best way to ensure they are being released properly? My method:

[beachPresenters addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:
                                @"Kayak rides",@"name",@"kayak_sm.png",@"smPhoto",@"kayak_med",@"medPhoto",@"Free kayak rides for kids",@"description",@"",@"Friday",
                                @"All day! 10.00am - 6.00pm",@"Saturday",@"",@"Sun",@"Beach",@"stage",@"Blah blah blah",@"blurb",nil]];

Upvotes: 0

Views: 262

Answers (3)

indiantroy
indiantroy

Reputation: 1503

You can have implementation like below:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:
                             @"Kayak rides",@"name",@"kayak_sm.png",@"smPhoto",@"kayak_med",@"medPhoto",@"Free kayak rides for kids",@"description",@"",@"Friday",
                             @"All day! 10.00am - 6.00pm",@"Saturday",@"",@"Sun",@"Beach",@"stage",@"Blah blah blah",@"blurb",nil];

[beachPresenters addObject:dict];
[dict release];

or

NSMutableDictionary *dict = [[[NSMutableDictionary alloc]initWithObjectsAndKeys:
                             @"Kayak rides",@"name",@"kayak_sm.png",@"smPhoto",@"kayak_med",@"medPhoto",@"Free kayak rides for kids",@"description",@"",@"Friday",
                             @"All day! 10.00am - 6.00pm",@"Saturday",@"",@"Sun",@"Beach",@"stage",@"Blah blah blah",@"blurb",nil] autorelease];

Upvotes: 0

Extra Savoir-Faire
Extra Savoir-Faire

Reputation: 6036

Your array beachPresenters retains the mutable array you created, but your array as created in your example already has a retain count of one. So even if you dispose of beachPresenters, your dictionary will still be retained, i.e., leaked.

Use [NSMutableDictionary dictionaryWithObjectsAndKeys:] instead.

Upvotes: 1

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

beachPresenters (I assume it's an array) takes ownership of the dictionary, so the +1 to the reference count caused by +alloc/-init of the dictionary is not balanced. Thus, the dictionary is leaked.

Use the convenience method equivalent to balance the retain:

NSDictionary *presenter = [NSDictionary dictionaryWithObjectsAndKeys: ...];
[beachPresenters addObject: presenter];

Upvotes: 1

Related Questions