Reputation: 726
I am making a game with Swift using SpriteKit.
I am using interface builder to position all my buttons (menu, retry etc) so i can use auto layout. I then display these buttons in the SKScene using NSNotificationCenter in a gameover function. I have no problem using NSNotificationCenter to display UIKit things in an SKScene.
Here is my problem i will try and explain as best i can.
When you get gameover a UIButton named retry gets displayed. I set up an NSNotificationCenter observer in the SKScene for the retry function and i call postNotificationName in the IBAction for the button in the viewController. The notification works perfect when i first load the game. I can play and retry and play and retry.
However when i return to main menu and load the game again and press retry the game crashes. Sometimes its just (lldb). Other times its unrecognized selector sent to instance.
Here is the code i have so far: This is the 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)
}
This is the 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")
}
Why does this happen? Why does the observer work first for the first play but then fail after i leave and return to the view? If you need anymore information just post a comment. Any help would be really appreciated!
Upvotes: 2
Views: 1010
Reputation: 700
You need to remove GameScene as an observer from NSNotificationCenter when the object is deinitialized.
The code below should fix your issue.
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
Upvotes: 5