iPhone Memory Management

后端 未结 3 477
渐次进展
渐次进展 2021-01-20 06:14

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 variab

3条回答
  •  时光说笑
    2021-01-20 07:06

    NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
    

    Here, language does not need to be released because objectAtIndex: autoreleases it for you. By convention, you own an object if you've alloced, newed, or copyed it, otherwise you don't.

    self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImageName]];
    

    Here, the UIColor object does need to be released (because you alloced it).

    NSString *backgroundImageName = [[NSString alloc] init];
    backgroundImageName = [NSString stringWithFormat:@"background-%@.png",language];
    

    Here the string returned by [[NSString alloc] init] does need to be released (because you've alloced it). However, the next line changes backgroundImageName to point to that a new autoreleased string, losing the last reference to the original string without releasing it (a memory leak). backgroundImageName should not be released because it is already autoreleased.

    You can avoid the leaks by releasing the UIColor and eliminating the unused string. For example:

    NSString *backgroundImageName = [NSString stringWithFormat:@"background-%@.png",language];
    

    ... and ...

    UIColor* backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImageName]];
    self.view.backgroundColor = backgroundColor;
    [backgroundColor release];
    

提交回复
热议问题