从app delegate暂停场景时Spritekit游戏崩溃

时间:2014-06-29 05:35:02

标签: ios sprite-kit

我试图在用户离开应用程序或使用以下代码点击广告时暂停游戏:

 SKView *view = (SKView *)self.window.rootViewController.view;
    view.paused = YES;

这曾经用于暂停游戏,但由于其他一些事情正在进行,我最终添加了另一个视图控制器来处理标题场景,并使一切正常,但由于某种原因暂停代码现在没有'工作,我得到以下错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setPaused:]: unrecognized selector sent to instance 0x170174280'

请注意,我仍然可以使用

在我的场景中暂停
self.scene.view.paused = YES;

有谁知道为什么会这样?通过阅读其他一些相关问题,我可以看到使用NSNotification可能有用吗?另一种选择是添加一个观察者?有谁知道为什么我正在使用的暂停代码不再适用于appDelegate以及我可以做些什么来解决这个问题?


3 个答案:

答案 0 :(得分:1)

在appDelegate中添加一个新方法:

- (SKView *)getGameView {
    NSArray *viewControllers = self.window.rootViewController.childViewControllers;
    for (UIViewController *vc in viewControllers) {
        if ([vc.view isKindOfClass:[SKView class]]) {
            SKView *view = (SKView *)vc.view;
            return view;
        }
    }
    return nil;
}

现在......修改您的代码:

SKView *view = (SKView *)self.window.rootViewController.view;
view.paused = YES;

为:

SKView *view = [self getGameView];
   if (view) {
       view.paused = YES; //or NO
      }

答案 1 :(得分:0)

rootViewController很可能不是ViewControllerSKViewrootViewController.view不是SKView

使用NSNotificationCenter而非尝试直接从AppDelegate暂停游戏:

@interface GameSceneViewController

@property (nonatomic, weak) IBOutlet SKView *skView;

@end

@implementation GameSceneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pause) name:@"pauseView" object:nil];
}
- (void)pause {
    self.skView.pause = YES;
}

@end

然后只需致电

[[NSNotificationCenter defaultCenter] postNotificationName:@"pauseView" object:nil];

答案 2 :(得分:0)

修改AppDelegate中的代码:

  • WillResignActive:

    -(void)applicationWillResignActive:(UIApplication *)application {
    
        YourViewController *viewGame = [[UIStoryboard storyboardWithName: StoryboardName bundle: nil] instantiateViewControllerWithIdentifier: identifier];
    
        SKView *view = (SKView *)viewGame.view.window;
        view.paused = YES;
    
    }
    
  • 和DidBecomeActive:

    - (void)applicationDidBecomeActive:(UIApplication *)application {
    
    if (!self.window.rootViewController.view)  {
        YourViewController *viewGame = [[UIStoryboard storyboardWithName: StoryboardName bundle: nil]instantiateViewControllerWithIdentifier: identifier];
    
        SKView *view = (SKView *)viewGame.view.window;
        view.paused = NO;
       }
    }