I have several places where I need to display an alert and handle the dismiss operation in the same way, namely take them to the same view controller. Instead of duplicating the alert specific code in all those places, I created a separate class like below:
AlertUtility.h:
@interface AlertUtility : NSObject {
}
- (void) displayAlert;
@end
AlertUtility.m:
@implementation AlertUtility {
- (void) displayAlert {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:... message:...
delegate:self cancelButtonTitle:... otherButtonTitles:nil] autorelease];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
// Create another view controller and display its views
[self release] // Release current object because I'm not releasing it where I create it
}
}
Where I need to use this alert (i.e. in MyViewController), I have the following:
MyViewController.m:
AlertUtility *utility = [[AlertUtility alloc] init];
[utility displayAlert];
As you can see, I am not releasing the utility object here (which I should since I own it), but rather in the didDismissWithButtonIndex method of the AlertUtility class. I am clearly missing something here.
I've tried autoreleasing the utility object but then by the time the didDismissWithButtonIndex method is 'called' on the utility object, that object was already released (due to the autorelease).
I've tried making the displayAlert method static (and calling it with [AlertUtility displayAlert];
), but then the didDismissWithButtonIndex is never called.
Should I just release the current object from within the didDismissWithButtonIndex method, like I do now, or is there a way to release it in MyViewController instead (without creating a AlertUtility property for the current class)?
Thanks!
EDIT Should I use the Singleton pattern instead maybe?