views:

103

answers:

1

Consider the following method, where I build a string and return it. I would like to release the building blocks of the string, but then the string is based on values that no longer exists. Now what?

Am I leaking memory and if so, how can I correct it?

- (NSString) getMiddahInEnglish:(int)day{
NSArray *middah = [[NSArray alloc] initWithObjects:@"Chesed", @"Gevurah", @"Tiferes", @"Netzach", @"Hod", @"Yesod", @"Malchus"];
NSString *firstPartOfMiddah = [NSString stringWithFormat: @"%@", [middah objectAtIndex: ((int)day% 7)-1]];
NSString *secondPartOfMiddah = [NSString stringWithFormat: @"%@", [middah objectAtIndex: ((int)day / 7)]];

NSString *middahStr = [NSString string@"%@ She'bi@%", firstPartOfMiddah, secondPartOfMiddah];

[middah release];
[firstPartOfMiddah release];
[secondPartOfMiddah release];

return middahStr;

}

At the end of the method, the return string, middahStr has not been released. Is this a problem? Am I leaking memory?

+4  A: 

Quite the opposite: You are over-releasing.

middah you alloc and init. Then you release it. All is well.

firstPartOfMiddah and secondPartOfMiddah, you call an NSString "stringWith" convenience method. This is equivalent to invoking alloc, init, and autorelease. Your releasing them is a mistake, as they are essentially given to autorelease to release later.

middahStr you call the convenience method, but return it. All is well. It will be released later by the autorelease pool.

Rule of thumb (I'm sure there are plenty of exceptions): If you don't alloc it, don't release it.

Jon Reid
so I can just remove the second and third `release` and then I'm all good?
Moshe
From one unicorn to another! Have the avatars been hacked?
Jon Reid
Moshe: Yes, that should do it.
Jon Reid
@Jon - Thanks. 4 minutes until I can accept this answer.
Moshe
Why don't you use Instruments to detect memory leaks? caveat emptor: sometimes they give false positives :)
zakovyrya
@zakovr]yrya - I was confused by my code, my concern was not the leak, but the proper way to build the string without leaking. By the way, what does `emptor` mean?
Moshe
Read this to understand memory management in Objective-C:http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/MemoryMgmt/MemoryMgmt.htmlI know, it's long, but you're gonna need it to have a clear picture.In regards to emptor: http://en.wikipedia.org/wiki/Caveat_emptor
zakovyrya
@zakovyrya - According to the wiki, `emptor`= `buyer`? Cool. I learned me some Latin tonight. Awesome! Thanks.
Moshe
Instruments is just a tool. There's nothing like learning the idioms. :)
Jon Reid
@Jon -- agreed.
Moshe