2012-10-10 20 views
3

我在ViewController以外的班级中有UIAlertView代表团遇到问题。 一切都很好,直到用户点击按钮OK - 然后应用程序崩溃与UIAlertViewDelegate在单独的班级崩溃应用程序

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 delegatenil - 没有委托的作品。

任何线索有什么不对?

回答

8

在该方法中:

- (void)viewDidLoad 
{ 
    DataModel *dataModel = [[DataModel alloc] init]; 
    [dataModel ShowMeAlert]; 

    [super viewDidLoad]; 
} 

您正在分配将由ARC在范围的端部被重新分配一个的DataModel局部变量。因此,当解雇时,你的代表不在那里了。修复此问题的方法是将DataModel存储在视图控制器的strong属性中。这样它就不会被释放。你会这样做:

- (void)viewDidLoad 
{ 
    self.dataModel = [[DataModel alloc] init]; 
    [self.dataModel ShowMeAlert]; 

    [super viewDidLoad]; 
} 
+0

谢谢一堆 - 它的作品!我有很多东西要学习...... – gutaker