在alertView中设置委托:self.delegate,其中self.delegate实现UIAlertViewDelegate协议

时间:2014-06-23 15:18:44

标签: objective-c xcode delegates uialertview uialertviewdelegate

在我的ViewController中,我实现了UIAlertViewDelegate,在我的模型中,我有一个方法,它创建一个UIAlertView,委托设置为self.delegate,它是ViewController的一个实例。然后我尝试像这样调用willPresentAlertView(在模型中):

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid operation"
            message:@"Cannot divide by 0!"
            delegate:self.delegate
            cancelButtonTitle:@"Cancel"
            otherButtonTitles:@"Undo division",nil];
[self.delegate willPresentAlertView:alert];

willPresentAlertView在ViewController中实现,如下所示:

- (void)willPresentAlertView:(UIAlertView *)alertView
{
    [alertView show];
}

我在调用[alert show]时收到错误主题1:EXC_BAD_ACCESS(代码= 2,地址= 0xbf7fff6c)

如果我将委托设置为nil或自我,它可以正常工作,但是当我按下警告上的按钮时,我想调用alertView:alertView clickedButtonAtIndex:buttonIndex,这不会对代理设置为nil或者自我。只有ViewController实现了这些方法,为什么它应该是self.delegate,或者?

我希望模型调用警报,但我希望ViewController处理警报方法,例如alertView:alertView clickedButtonAtIndex:buttonIndex

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

它应该是自我[self willPresentAlertView:alert]

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid operation"
            message:@"Cannot divide by 0!"
            delegate:self //self
            cancelButtonTitle:@"Cancel"
            otherButtonTitles:@"Undo division",nil];
[self willPresentAlertView:alert];//self again