2012-10-10 3 views
3

ViewController 이외의 클래스에서 UIAlertView 위임에 어려움이 있습니다.별도의 클래스에있는 UIAlertViewDelegate가 응용 프로그램을 중단 함

#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이

Thread 1: EXC_BAD_ACCESS (code=2, address 0x8) 

ViewController.h와 다음 응용 프로그램 충돌 - 사용자가 OK 버튼을 클릭 할 때까지 다 괜찮습니다 .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