切换视图控制器后第二次调用方法的问题

Issue with calling method a second time after switching view controllers

好的。所以我正在使用 objective C 在 sprite kit 中开发游戏。我有一个我调用的方法,它使用 viewcontroller skscene 是 运行 的来源,在游戏结束时调用 uialertcontroller。在警报视图中按下 ok 按钮后,我将返回主菜单视图控制器。这很好用。然而,当我再次去玩游戏,切换回游戏 viewcontroller 并结束另一场游戏时,uialertview 无法触发。我收到一条错误消息:

Warning: Attempt to present <UIAlertController: 0x14205d600> on <GameViewController: 0x141e176f0> whose view is not in the window hierarchy!

这是我调用 UIAlertController 的代码:

UIAlertController * gameOverAlert = [UIAlertController alertControllerWithTitle: @"Game Over!" message: textscore preferredStyle: UIAlertControllerStyleAlert];

//add the button that will take us back to the main menu
UIAlertAction *okButton = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
    [UIApplication.sharedApplication.keyWindow.rootViewController.presentedViewController performSegueWithIdentifier:@"backToTheMenuNotFuture" sender:self];
}];

[gameOverAlert addAction: okButton];


[UIApplication.sharedApplication.keyWindow.rootViewController.presentedViewController presentViewController: gameOverAlert animated:true completion: nil];

这是我进入游戏模式时的代码viewcontroller:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"gotoPlay"]){
        gameController = (GameViewController *)segue.destinationViewController;
        gameController.playingMusic = musicHave;

    }

}

正如我所说,这在第一场比赛中运行良好,但是当您再次参加比赛并输掉第二次比赛时,就会出现错误。

已解决:

(isDismissed 是一个从 0 开始的 int 值)

//add the button that will take us back to the main menu
UIAlertAction *okButton = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
    isDismissed = 1;
    [UIApplication.sharedApplication.keyWindow.rootViewController.presentedViewController performSegueWithIdentifier:@"backToTheMenuNotFuture" sender:self];

}];

[gameOverAlert addAction: okButton];


[UIApplication.sharedApplication.keyWindow.rootViewController.presentedViewController presentViewController: gameOverAlert animated:true completion: nil];
if(isDismissed == 1){
    [UIApplication.sharedApplication.keyWindow.rootViewController.presentedViewController dismissViewControllerAnimated:NO completion: nil];
    [UIApplication.sharedApplication.keyWindow.rootViewController.presentedViewController presentViewController: gameOverAlert animated:true completion: nil];
    [UIApplication.sharedApplication.keyWindow.rootViewController.presentedViewController performSegueWithIdentifier:@"backToTheMenuNotFuture" sender:self];
}

}

所以这里的问题和评论中一样是有多个 gameviewcontroller 实例 运行 同时出现。上面的代码取消了 'current' gameviewcontroller,然后尝试 运行 我想要的原始代码。它可以工作,但是我不确定游戏是否会在每次 运行s 时释放旧的 gameviewcontroller 或创建更多副本。最后我看到它是这样的。如果它像它应该的那样解除分配那么它很好。如果不是,那么我认为消耗大约 8MB RAM 的游戏最终会导致 iPhone 滞后。如果确实发生这种情况,那么您显然已经玩了很长时间了,无论如何您真的应该休息一下。这不是错误,这是一个功能!