ios/xcode:UIAlert 未停止操作并单击“确定”导致应用程序崩溃

ios/xcode: UIAlert Not stopping action and clicking OK crashing app

将某些内容保存到核心数据后,我想显示一个警告以感谢用户。当用户单击“确定”时,我想关闭执行保存的模态视图控制器。

但是,警报并没有停止关闭控制器,而且当您点击“确定”时进一步导致应用程序崩溃。我的理解是,当控制器不再存在时,可能会发生这些崩溃。然而,在这种情况下,我会在关闭控制器之前启动警报。

谁能找出问题所在?

如有任何建议,我们将不胜感激。

代码:

if ([self.managedObjectContext save:&error]) {
            [self fireAlert];
            // Dismiss View Controller
            [self dismissViewControllerAnimated:YES completion:nil];

        } else {
            if (error) {
                NSLog(@"Unable to save record.");
                NSLog(@"%@, %@", error, error.localizedDescription);
            }
         }

-(void) fireAlert {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Thank you!" message:@"We appreciate your feedback" delegate:self
                                               cancelButtonTitle:@"OK" otherButtonTitles:nil];

    [alert show];
}

您正在关闭视图控制器,因此 delegate:self 导致崩溃,因为在

之后
[self dismissViewControllerAnimated:YES completion:nil];

self 不再可用。它被解除分配并向解除分配的对象发送消息导致崩溃。

如果您不想使用 UIAlertView 委托方法,请尝试制作 delegate:nil

或使用委托方法,确保您有 UIViewController <UIAlertViewDelegate>

然后

if ([self.managedObjectContext save:&error]) {
            [self fireAlert];

        } else {
            if (error) {
                NSLog(@"Unable to save record.");
                NSLog(@"%@, %@", error, error.localizedDescription);
            }
         }

-(void) fireAlert {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Thank you!" message:@"We appreciate your feedback" delegate:self
                                               cancelButtonTitle:@"OK" otherButtonTitles:nil];

    [alert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex 
{
   // Dismiss View Controller
   [self dismissViewControllerAnimated:YES completion:nil];
}