Search code examples
objective-cios6automatic-ref-counting

How do UIAlertView or UIActionSheet handle retaining/releasing themselves under ARC?


I want to create a similar class to UIAlertView which doesn't require a strong ivar.

For example, with UIAlertView, I can do the following in one of my UIViewController's methods:

UIAlertView *alertView     = [[UIActionSheet alloc] initWithTitle:nil
                                                          message:@"Foo"
                                                         delegate:nil
                                                cancelButtonTitle:@"Cancel"
                                                otherButtonTitles:nil];
[alertView show];

... and the actionSheet will not be dealloced until it is no longer visible.

If I were to try to do the same thing:

MYAlertView *myAlertView = [[MYAlertView alloc] initWithMessage:@"Foo"];
[myAlertView show];

... the myAlertView instance will automatically be dealloced at the end of the current method I am in (e.g. right after the [myAlertView show] line).

What is the proper way to prevent this from happening without having to declare myView as a strong property on my UIViewController? (I.e. I want myView to be a local variable, not an instance variable, and I would like the MYAlertView instance to be in charge of its own lifecycle rather than my UIViewController controlling its lifecycle.)

Update: MYAlertView inherits from NSObject, so it cannot be added to the Views hierarchy.


Solution

  • UIAlertView creates a UIWindow, which it retains. The alert view then adds itself as a subview of the window, so the window retains the alert view. Thus it creates a retain cycle which keeps both it and its window alive. UIActionSheet works the same way.

    If you need your object to stay around, and nothing else will retain it, it's fine for it to retain itself. You need to make sure you have a well-defined way to make it release itself when it's no longer needed. For example, if it's managing a window, then it should release itself when it takes the window off the screen.