Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIAlertView -show causing a memory leak

I'm relatively new to iPhone Development, so this may be my fault, but it goes against what I've seen. :)

I think that I'm creating a UIAlertView that lives just in this vaccuum of the 'if' statement.

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if(!data)
{
    // Add an alert
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                    message:@"Unable to contact server"
                                                   delegate:nil
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil];
    NSLog(@"retain count before show: %i", alert.retainCount);
    [alert show];
    NSLog(@"retain count before release: %i", alert.retainCount);
    [alert release];
    NSLog(@"retain count after release: %i", alert.retainCount);
    return nil;
}

However, the console logs baffle me.

retain count before show: 1
retain count before release: 6
retain count after release: 5

I've tried also adding:

alert = nil;

after the release. That makes the retain count 0, but I still show a leak. And if it helps, the leak's Responsible Frame is UIKeyboardInputManagerClassForInputMode. I'm also using OS 4 Beta 3.

So anyone have any ideas how a local UIAlertView's retain count would increment itself by 5 when calling -show?

Thanks for your help!

like image 589
Erik Avatar asked May 19 '10 01:05

Erik


1 Answers

This makes some sense if you realize that [alert show] doesn't immediately put the alert up on screen. I think what happens is that the [alert show] adds the alert to some queue somewhere in the system which retains it. It won't actually be shown until you return from this function and get back to the event loop. When it eventually gets dismissed those retain counts will get decremented and it will be released then.

If you were to log messages from UIAlertView's delegate routines, such as didPresentAlertView, I'll bet that doesn't happen until after your function ends, after you've "released" the alert. Release doesn't always mean deallocate, it is just relinquishing ownership. It only causes a dealloc if there are no owners left.

like image 57
progrmr Avatar answered Sep 22 '22 06:09

progrmr