Frank
Frank

Reputation: 2413

Odd coding pattern when releasing the UIAlertView

In a lot of code samples, also on the Apple documentation website, you will see this kind of pattern. The UIAlertView is called with "show" and "release" in sequence.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Panic!"
    message:@"The world is gonna explode!"
    delegate:nil cancelButtonTitle:@"Who cares?"
    otherButtonTitles:@"Boom!", nil];
[alert show];
[alert release];
NSLog(@"released!");

When you run this code, the "released!" log line will be shown while the UIAlertView box is still on screen. It seems like an odd pattern to me to release this object when it's still seen on screen. What is the idea behind this, isn't this against what is common with memory management? If this "show" call would be blocking, I could see how this pattern would be safely freeing the memory. But since the NSLog method is executed, it continues executing your code.

Upvotes: 3

Views: 787

Answers (3)

Bruno Domingues
Bruno Domingues

Reputation: 1015

If you examine the code you see that when the UIAlertView is being created it is being allocated too. So the retain count of the alert is 1 after that. If you read the apple documentation you will see that the [alert show] also increase the retain count of the UIAlertView. So, after that line the retain count will be 2. The line [alert release] will decrease the retain count to 1 again, because, for this code, isn't important to keep reference to the UIAlertView. So, after that, the retain count is 1, and the UIAlertView is being showed. When the user press the button to close the alert, the method that closes the alert will decrease the retain count to 0 and the memory will be freed

Upvotes: 0

anon
anon

Reputation:

release doesn’t mean that the object will be disposed off right away. It just means that your code doesn’t want to access it any more after that point. Other code (like the system frameworks) might and so they retained it.

Upvotes: 5

RolandasR
RolandasR

Reputation: 3047

[alert show]; retains UIAlertView

Upvotes: 4

Related Questions