Keller
Keller

Reputation: 17081

NSObject extending UIAlertViewDelegate crash?

I have a helper class that I want to display a UIAlertView then will perform some web service action. I would like to do it this way so I can re-use the alert view in other places.

I am declaring it like so:

@interface FBLinkHelper : NSObject <UIAlertViewDelegate>

I also have a method that will show the alert view:

- (void) showLinkDialog {
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Link account with Facebook?" message:@"Linking your account with Facebook extends your user experience. Link account?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
    [av show];
}

This is how I am showing the dialog:

    FBLinkHelper *fbLinkHelper = [[FBLinkHelper alloc] init];
    [fbLinkHelper showLinkDialog];

All seems pretty normal to me. It shows the alert view dialog, but when I click a button (either one) my app crashes without much to say in the console. I notice it only crashes when I have a UIAlertViewDelegate method in place, such as didDismissWithButtonIndex. Why is this happening?

Upvotes: 2

Views: 729

Answers (2)

otaviokz
otaviokz

Reputation: 382

I had the same case in an app I'm working at. If the delegate object isn't a strong (or retain in iOS prior to 5.0) property it might get deallocated right after the UIAlertView is shown.

Upvotes: 0

diatrevolo
diatrevolo

Reputation: 2822

-UPDATE-

The FBLinker instance was not a strong property of its caller, so the delegate callback went to a dangling pointer. OP reports making FBLinker strong took care of issue.

Original suggestion of making the class extend from UIView instead of NSObject had no effect, and is referenced here only for historical purposes.

Upvotes: 2

Related Questions