好的。所以我正在使用 Objective C 在 Sprite 套件中开发一个游戏。我有一个我称之为的方法,该方法使用运行 skscene 的 View Controller 来在游戏结束时调用 uialertcontroller。在警报 View 中按下“确定”按钮后,我会返回主菜单 View Controller 。这很好用。然而,当我再次玩游戏,切换回游戏 View Controller 并结束另一个游戏时,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];
这是当我模态到游戏 View Controller 时的代码:
-(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 实例。上面的代码关闭了“当前”游戏 View Controller ,然后尝试运行我想要的原始游戏 View Controller 。它有效,但是我不确定游戏是否会取消分配旧的游戏 View Controller 或在每次运行时创建更多重复项。最后我看到的是这样的。如果它像应有的那样解除分配,那就没问题了。如果不是这样,那么我认为这款消耗约 8MB RAM 的游戏最终会导致 iPhone 出现延迟。如果确实发生这种情况,那么显然您已经玩了很长时间,无论如何您都应该休息一下。这不是一个错误,而是一个功能!
关于ios - 切换 View Controller 后第二次调用方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389359/