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?
Quite the opposite: You are over-releasing.
middahyou alloc and init. Then you release it. All is well.firstPartOfMiddahandsecondPartOfMiddah, 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.middahStryou 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.