Question

I have a subclass of NSObject (MyCustomObject) that is instantiated and called to perform some logic and decide whether to display a UIAlertView. MyCustomObject implements the UIAlertViewDelegate protocol to perform some more logic and set some NSUserDefaults in alertView: clickedButtonAtIndex:. Where is it appropriate to release myCustomObject? If myCustomObject is no longer needed after the user clicks one of the buttons on the alert view, it is OK for myCustomObject to release itself in alertView: didDismissWithButtonIndex: ?

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"I'm UIAlertView's Delegate and I'm releasing myself");
    [self release];
}
Was it helpful?

Solution

I think it'd be better if you made a delegate protocol for your custom object, then have the owner of that object be its delegate. In your class's alert view delegate method, send the custom delegate a message so it can handle releasing your custom object.

If the object is autoreleased within the calling code, or the calling code tries to manually release your object itself, trying to self-release might produce unexpected behavior or even crash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top