0

我有 2 个视图控制器,ViewController1(VC1) 和 2(VC2)。在 VC2 中,我有一个后退和完成按钮。单击后退按钮时,它直接转到 VC1,完成后它会进行 api 调用,当它得到响应时,它会显示一个警报视图,然后单击确定会返回 VC1。现在,当我进行 api 调用时,加载栏会出现并在我得到响应时消失并显示AlertView. 但是,如果在加载消失的那几分之一秒内AlertView,如果我单击后退并且视图更改为 VC1 将弹出,则警报会出现在 VC1 上并导致崩溃。

这是一种罕见的情况,因为没有用户会故意尝试它,但我想知道是否可以在不禁用后退按钮的情况下管理该崩溃。我认为可能还有其他情况,例如我们正在进行异步调用,如果允许用户在等待响应时使用 UI,以及如果假设显示在另一个上的任何错误警报ViewController出现在另一个可能会导致崩溃因为警报所指的委托是前一个视图控制器的委托。那么有没有办法有效地处理这种崩溃呢?

//Alert View sample
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[message objectAtIndex:1] capitalizedString] message:[message objectAtIndex:0] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] ;
[alert setTag:701];
[alert show];

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([alertView tag] == 701)
        if (buttonIndex == 0)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }


}
4

1 回答 1

1

解决此问题的正确方法是使用实​​例变量来保留对警报视图的引用。

此实例变量应nilalertView:didDismissWithButtonIndex:委托方法中设置为。

在视图控制器的dealloc方法中,dismissWithClickedButtonIndex:animated:如果实例变量仍然设置,则调用。

假设_alertView是实例变量。

创建警报:

_alertView = [[UIAlertView alloc] initWithTitle:[[message objectAtIndex:1] capitalizedString] message:[message objectAtIndex:0] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] ;
[_alertView setTag:701];
[_alertView show];

更新您现有的alertView:clickedButtonAtIndex:方法:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if ([alertView tag] == 701) {
         _alertView.delegate = nil;            
         _alertView = nil;
        if (buttonIndex == 0) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

添加:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    _alertView = nil;
}

添加:

- (void)dealloc {
    if (_alertView) {
        _alertView.delegate = nil;
        [_alertView dismissWithClickedButtonIndex:_alertView.cancelButtonIndex animated:NO];
        _alertView = nil;
    }
}
于 2014-05-07T05:47:58.020 回答