ShogoDodo
ShogoDodo

Reputation: 63

Why does Instruments think this is leaking memory?

I have an About View which I push onto a NavigationController. The view has one UILabel which is connected to an IBOutlet. In viewDidLoad I populate the UILabel with the bundle version number (a string). Testing with instruments suggested that the line marked with a comment is leaking memory: -

viewDidLoad {
    [super viewDidLoad];

    self.title = @"About";
    // Line below is the suggested culprit ***
    NSString *versionLabel = [[NSString alloc] initWithFormat:@"Version %@", 
                              [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey]];

    self.applicationVersion.text = versionLabel;
    [versionLabel release];
    versionLabel = nil;
}

I'm assuming it is suggesting the NSString and not anything else on the line ...

My questions is Why ?

Upvotes: 2

Views: 210

Answers (3)

Peter N Lewis
Peter N Lewis

Reputation: 17811

It may actually be the mainBundle or infoDictionary that is leaking - it is possible that the system is caching one or other of those and thus they are being created and then never released.

Try adding in to your applicationDidFinishLaunching the code:

[[NSBundle mainBundle] infoDictionary];

Without any other code and see if Leaks points to that line as the location of the leak. In that case, caching is the issue and you can ignore it.

Upvotes: 0

zpesk
zpesk

Reputation: 4353

You don't even need to create an instance of NSString in that case, simply use the following method that acts on the NSString class (not an instance):

NSString *versionLabel = [NSString stringWithFormat:@"Version %@", 
                                             [[[NSBundle mainBundle] infoDictionary] 
                                            objectForKey:(NSString*)kCFBundleVersionKey]];

If you use NSString this way, you do not have to release versionLabel because memory was never allocated.

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299355

My suspicion is that you're leaking the applicationVersion UILabel. That will cause the string to leak as a by-product. The most common reason for this on iPhone is failure to follow the NIB memory management rules.

Upvotes: 2

Related Questions