2013-04-15 30 views
0

我嘗試實現處理uialertview的viewcontroller類別。它需要實現-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex,如果viewcontroller還需要顯示警報視圖,不要搞砸。爲此,我將uialertview的委託設置爲類別內的虛擬對象而不是自我。但是當alertview中的其中一個按鈕被點擊時,我的應用程序崩潰exc_bad_access。下面的代碼有什麼問題?在類別中實現UIAlertView委託方法

//Dummy handler .h 

@interface dummyAlertViewHandler : NSObject <UIAlertViewDelegate> 

@property (nonatomic, weak) id delegate; 

//.m 
-(id) initWithVC:(id) dlg 
{ 
    self = [super init]; 
    if (self != nil) 
    { 
     self.delegate = dlg; 
    } 
    return self; 
} 

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 
    if (buttonIndex == 1) 
    { 
     [self mainMenuSegue]; //There is no problem with the method 
    } 
} 

//Category .h 
#define ALERT_VIEW_DUMMY_DELEGATE_KEY "dummy" 
@property (nonatomic, strong) id dummyAlertViewDelegate; 

//Category .m 
@dynamic dummyAlertViewDelegate; 

- (void)setDummyAlertViewDelegate:(id)aObject 
{ 
    objc_setAssociatedObject(self, ALERT_VIEW_DUMMY_DELEGATE_KEY, aObject, OBJC_ASSOCIATION_ASSIGN); 
} 

- (id)dummyAlertViewDelegate 
{ 
    id del = objc_getAssociatedObject(self, ALERT_VIEW_DUMMY_DELEGATE_KEY); 

    if (del == nil) 
    { 
     del = [[dummyAlertViewHandler alloc] initWithVC:self]; 
     self.dummyAlertViewDelegate = del; 
    } 

    return del; 
} 

-(void) mainMenuSegueWithConfirmation 
{ 
    UIAlertView *ruSure = [[UIAlertView alloc] initWithTitle:@"Confirm leave" 
message:@"Are you sure you want to leave this game?" 
delegate:self.dummyAlertViewDelegate 
cancelButtonTitle:@"No" 
otherButtonTitles:@"Yes", nil]; 

    [ruSure show]; 
} 
+0

究竟碰撞發生在哪一行? – matt

+0

它直接跳轉到裝配我不能跟蹤它。我啓用了所有異常的斷點,我想它不會引發異常。 – guenis

回答

1

你的問題是這樣的一行:

objc_setAssociatedObject(self, ALERT_VIEW_DUMMY_DELEGATE_KEY, aObject, OBJC_ASSOCIATION_ASSIGN); 

具體的OBJC_ASSOCIATION_ASSIGN使你的相關物品不予保留。爲您設計在所有的工作,你將需要改變,要OBJC_ASSOCIATION_RETAIN,像這樣:

objc_setAssociatedObject(self, ALERT_VIEW_DUMMY_DELEGATE_KEY, aObject, OBJC_ASSOCIATION_RETAIN); 
+0

非常感謝我從博客中獲得了對象關聯部分,但沒有想到玩這些參數。 – guenis