Reputation: 181
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
ViewController
- works perfectly.UIAlertDelegation
method ...didDismissWithButtonIndex...
-
works without delegation. UIAlertView delegate
to nil
-
works without delegation.Any clues what's wrong?
Upvotes: 3
Views: 698
Reputation: 69047
In this method:
- (void)viewDidLoad
{
DataModel *dataModel = [[DataModel alloc] init];
[dataModel ShowMeAlert];
[super viewDidLoad];
}
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 DataModel
in a strong
property of your view controller. This way it will not be deallocated. The you would do:
- (void)viewDidLoad
{
self.dataModel = [[DataModel alloc] init];
[self.dataModel ShowMeAlert];
[super viewDidLoad];
}
Upvotes: 8