UIAlertViewDelegate in separate class crashes application



除了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];
}

最新更新