I’m having difficulties with UIAlertView delegation in class other than ViewController.
Everything is fine until user clicks the OK button – then app crashes with
Thread 1: EXC_BAD_ACCESS (code=2, address 0x8)
ViewController.h:
#import <UIKit/UIKit.h>
#import "DataModel.h"
@interface ViewController : UIViewController
@end
ViewController.m:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
DataModel *dataModel = [[DataModel alloc] init];
[dataModel ShowMeAlert];
[super viewDidLoad];
}
@end
DataModel.h
#import <Foundation/Foundation.h>
@interface DataModel : NSObject <UIAlertViewDelegate>
- (void)ShowMeAlert;
@end
DataModel.m
#import "DataModel.h"
@implementation DataModel
- (void)ShowMeAlert;
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Info" message:@"View did load!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
#pragma mark - UIAlertView protocol
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSLog(@"Index: %d", buttonIndex);
}
@end
- If code for showing alert and it’s delegation methods is in
ViewController– works perfectly. - When I remove
UIAlertDelegationmethod...didDismissWithButtonIndex...–
works without delegation. - When I set
UIAlertView delegatetonil–
works without delegation.
Any clues what’s wrong?
In this method:
you are allocating a DataModel local variable which will be deallocated by ARC at the end of the scope. Hence, when dismiss is executed, your delegate is not there anymore. The fix for this is to store your
DataModelin astrongproperty of your view controller. This way it will not be deallocated. The you would do: