另一个视图控制器上的UIAlertView崩溃问题

我有2个视图控制器, ViewController 1(VC1)和2(VC2)。 在VC2中,我有一个后退和完成button。 在点击返回button时,它直接进入VC1,在完成后进行一次api调用,当它得到一个响应时,它显示一个警报视图,点击OK返回到VC1。 现在,当我进行api调用时,出现一个加载条,并在获取响应并显示AlertView时消失。 但是,如果在加载消失的第二秒的时间内,如果我点击返回并且视图改变为VC1, AlertView将popup,则VC1上将出现警报,并导致崩溃。

这是一个罕见的情况,因为没有用户会故意尝试,但我想知道是否可以在不禁用后退button的情况下pipe理崩溃。 我认为可能有其他实例这样的情况下,如果我们正在进行asynchronous调用,并且如果允许用户在等待响应时使用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]; } } 

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

alertView:didDismissWithButtonIndex: delegate方法中,应将此实例variables设置为nil

在视图控制器的dealloc方法中,如果实例variables仍然被设置,你可以调用dismissWithClickedButtonIndex:animated:

假设_alertView是实例variables。

创build警报:

 _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; } }