I’m working on an app and I’d like to make sure that I’m managing memory properly and releasing everything that I should. In my viewDidLoad method I allocate some variables in determining which background to apply to the view (for internationalization) and the app works fine if I don’t release them.
The problem is that if I release the variables the app will crash. Code from viewDidLoad is below:
// Set the background image based on the phone's preferred language
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *backgroundImageName = [[NSString alloc] init];
backgroundImageName = [NSString stringWithFormat:@"background-%@.png",language];
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImageName]];
... do some more initialization stuff ...
// IF THE FOLLOWING ARE RELEASED THE APP WILL CRASH!!!
//[backgroundImageName release];
//[language release];
Why would releasing the backgroundImageName and language variables cause the app to crash?
Here,
languagedoes not need to be released becauseobjectAtIndex:autoreleases it for you. By convention, you own an object if you’vealloced,newed, orcopyed it, otherwise you don’t.Here, the
UIColorobject does need to be released (because youalloced it).Here the string returned by
[[NSString alloc] init]does need to be released (because you’vealloced it). However, the next line changesbackgroundImageNameto point to that a new autoreleased string, losing the last reference to the original string without releasing it (a memory leak).backgroundImageNameshould not be released because it is already autoreleased.You can avoid the leaks by releasing the
UIColorand eliminating the unused string. For example:… and …