除了ViewController
之外,我在课堂上UIAlertView
委派时遇到困难。一切都很好,直到用户单击OK
按钮 - 然后应用程序崩溃
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
- 则正常工作。 - 当我删除
UIAlertDelegation
方法时...didDismissWithButtonIndex...
-无需委派即可工作。 - 当我将
UIAlertView delegate
设置为nil
时 -无需委派即可工作。
有什么线索吗?
在此方法中:
- (void)viewDidLoad
{
DataModel *dataModel = [[DataModel alloc] init];
[dataModel ShowMeAlert];
[super viewDidLoad];
}
您正在分配一个 DataModel 局部变量,该变量将由 ARC 在作用域结束时解除分配。因此,当执行解除时,您的委托不再存在。解决此问题的解决方法是将DataModel
存储在视图控制器的strong
属性中。这样就不会解除分配。你会做的:
- (void)viewDidLoad
{
self.dataModel = [[DataModel alloc] init];
[self.dataModel ShowMeAlert];
[super viewDidLoad];
}