将NSNotificationCenter与SkScene一起使用到UIViewController

Poi*_*pps 2 nsnotificationcenter ios sprite-kit swift

我正在使用SpriteKit与Swift进行游戏.

我正在使用界面构建器来定位我的所有按钮(菜单,重试等),所以我可以使用自动布局.然后,我在游戏功能中使用NSNotificationCenter在SKScene中显示这些按钮.使用NSNotificationCenter在SKScene中显示UIKit的东西没问题.

这是我的问题,我将尽力解释.

当你获得游戏时,会显示一个名为retry的UIButton.我在SKScene中设置了一个NSNotificationCenter观察器用于重试功能,我在IBAction中为viewController中的按钮调用postNotificationName.当我第一次加载游戏时,通知工作正常.我可以玩,重试,玩和重试.

然而,当我返回主菜单并再次加载游戏并按重试游戏崩溃.有时它只是(lldb).其他时候将其无法识别的选择器发送到实例.

这是我到目前为止的代码:这是ViewController

class GameSceneViewController: UIViewController{

 @IBOutlet weak var homeBtn: UIButton!
@IBOutlet weak var retryBtn: UIButton!

var userDefaults = NSUserDefaults.standardUserDefaults()

//MARK: Button Actions
@IBAction func returnToMenu(sender: UIButton) {

    self.dismissViewControllerAnimated(true, completion: nil)
}

@IBAction func retryGame(sender: UIButton) {

    NSNotificationCenter.defaultCenter().postNotificationName("retrygame", object: nil)

}
    override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    var scene: GameScene!
    let skView = view as SKView
    skView.showsFPS = false
    skView.showsNodeCount = true
    skView.showsPhysics = false

    skView.ignoresSiblingOrder = true

    scene = GameScene(size: skView.bounds.size)
    scene.scaleMode = .AspectFill

    skView.presentScene(scene)

}
Run Code Online (Sandbox Code Playgroud)

这是GameScene:

class GameScene: SKScene {

//MARK: The View
override func didMoveToView(view: SKView) {

    self.backgroundColor = UIColor.grayColor()
    setUpGame()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "retry", name: "retrygame", object: nil)

}

func retry(){

    print("test")
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?为什么观察者在第一次播放时首先工作但在我离开并返回视图后失败?如果您需要更多信息,请发表评论.任何帮助将非常感激!

Cez*_*zar 5

当对象被取消初始化时,您需要从NSNotificationCenter中删除GameScene作为观察者.

以下代码可以解决您的问题.

deinit {
  NSNotificationCenter.defaultCenter().removeObserver(self)
}
Run Code Online (Sandbox Code Playgroud)