简体   繁体   中英

UIAlertView in ARC app

I have iphone sample application with one button. On tap it calls code:

UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"test"
                          message:@"test"
                          delegate:self
                          cancelButtonTitle:@"Ok"
                          otherButtonTitles: nil];
[alert show];

Application has ARC enabled.

The problem is that if I click on OK button in alert, application crashes with EXC_BAD_ADDRESS - probably because of alert is already removed by arc.

What is recommended way to solve this? without adding property to viewcontroller

thanks

My guess is either you haven't implemented the UIAlertViewDelegate methods or that self has gone out of scope.

If you don't care about being alerted when someone dismisses the alert box, change the delegate to nil. eg

UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"test"
                          message:@"test"
                          delegate:nil
                          cancelButtonTitle:@"Ok"
                          otherButtonTitles: nil];
[alert show];

The delegate property of UIAlertView is declared as a weak reference (indicated by the assign keyword). This means ARC will not increment the retain count and you will need to retain a reference to the delegate object (whether it is self or a separate object). This reference should be maintained for the full life of the UIAlertView.

@property(nonatomic,assign) id /*<UIAlertViewDelegate>*/ delegate;    // weak reference

I assume that the reason for this is to prevent a loop and failure to release as in the common case the object creating the UIAlertView will retain a reference to it and be it's delegate so closing the loop and preventing release.

This is probably a common pattern for delegates but I hadn't realised until I hit exactly the same issue. I ran in the simulator with zombie detection enabled and it clearly indicated the reference counts and I saw that it was not being retained by the UIAlertView. That was when I checked the header file.

The answer to this question provides some additional information about delegates on system classes and the assign keyword. iPhone ARC Release Notes - dealloc on system classes delegates?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM