views:

50

answers:

3

I have this class that shows a popup. I do a alloc-init on it and it comes up.

DarkVader* darkPopUp = [[DarkVader alloc] init:theButton helpMessage:[theButton.titleLabel.text intValue] isADay:NO offset:0];

It shows itself and if the user presses Ok it disappears. When do I release this?

I could do a [self release] in the class when the OK button is pressed. Is this correct? If I do this the Analyzer says it has a retain count of +1 and gets leaked in the calling function. If I release it just after the alloc-init the Analyzer says it has a retain count of +0 and i should not release it.

    DLog(@"DarkVader retain count: %i", [darkPopUp retainCount]);

says it has a retain count of 2. I'm confused.

In short my question is: How do I release an object that gets initialized does some work and ends but no one is there to release it in the calling function.

A: 

My suggestion would be to use

[self autorelease];

when the view is closing itself. Although if you look at various standard views, then all implement callbacks to a delegate that becomes responsible for closing them; this let's the launching object be responsible for releasing the view as well. You also don't make it clear how your view (or is it a view controller) is displayed.

Paul Lynch
A: 

You could do something similar to what existing Cocoa Touch classes does. For example, see how you show an UIAlertView:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

It's quite clear that UIAlertView does a [self retain], or more likely, gets retained when added as a subview somewhere on the screen somewhere in the show method.

There are some Cocoa Touch classes that indeed (just as Paul mentioned) do not support this way of release at once, but instead calls a delegate method and excepts the receiver to release it.

I'd say the answer is, if your DarkVader is an UIView, you should let the subview-retain take care of the retain count. If it's a UIViewController or a custom helper class, you have a few options, the delegate way being a simple and straight forward one.

alleus
A: 

If you want a custom pop-up in the style you described you should probably already be subclassing UIAlertView to begin with. Then you can use it's already implemented retain/release functionality.

thelaws