2012-10-10 21 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