为什么 applicationWillResignActive 方法不起作用?

Why does the applicationWillResignActive method not work?

在我的 GameScene.m 中,我有一个名为 wentToBackGround 的方法。此方法由 AppDelegate 中的 applicationWillResignActive 调用:

GameScene *gameScene = [[GameScene alloc]init];
[gameScene wentToBackground];

在 wentToBackGround 中,我像这样移动我的玩家精灵(只是为了测试它是否有效):

-(void)wentToBackground {
  NSLog(@"BG");
  self.player.position = CGPointMake(CGRectGetMidX(self.frame), 1000);
}

NSLog 有效,但玩家位置保持不变。这是不是因为SpriteKit一进入BG就自动暂停一切。我该如何解决这个问题。我最终希望有一个暂停菜单,在用户离开应用程序时立即打开。 如何正确执行此操作?

我认为它也可能不起作用,因为我创建了 GameScene 的新实例。如何使用旧实例? (旧实例是在另一个场景中创建的,TitleScene

I think it also might not work, because I made a new instance of the GameScene

正确,你明白了!做得好。请记住(我认为您现在已经掌握了这一点)class 只是一个模板。您应用中的对象是实例,您可以为一个 class 创建多个实例。所以当你说

[[GameScene alloc]init]

您正在制作一个实例。这是合法的,但毫无意义;向它发送 wentToBackground 消息没有任何用处,因为它不在您的界面中。您要与之对话的 GameScene 实例,即您界面中的实例,在别处。

获取对特定现有实例的引用可能很棘手。有时您必须提前安排事情才能使其成为可能。但是,我认为您可以在这里避免整个问题。 UIApplication 不仅有一个应用程序委托方法,还有一个 notification 让你知道你将退出活动。因此,只需让 GameScene 注册该通知,现在您根本不必涉及应用程序委托。

这是关于该通知的文档:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/#//apple_ref/c/data/UIApplicationWillResignActiveNotification

任何对象都可以注册通知,因此这是一种确定您的 GameScene 希望收到停用通知的方法。