pRivaT3 BuG pRivaT3 BuG - 4 months ago 16
iOS Question

Whats the correct way, using "init" or "didmove"?

Language: Swift 3.0 --- IDE : Xcode 8.0 beta 2 --- Project : iOS Game (SpriteKit)

I create a game for iOS and i know Apple is really strict with their rules to accept the app/game. So i want to know which is the correct way to setup a game.

I learned from google to create a new SpriteKit Project and do the following setup :

In GameViewController.swift clear viewDidLoad() and add all this :

override func viewDidLoad() {
super.viewDidLoad()
let skView = self.view as! SKView

let scene = GameScene(size: skView.bounds.size)
scene.scaleMode = .aspectFit

skView.presentScene(scene)
}


In GameScene.swift delete everything and leave this code :

import SpriteKit

class GameScene: SKScene {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

override init(size: CGSize) {
super.init(size: size)
// add all the code of the game here...
}

}


and develop my game inside override init

But I think thats actually wrong to start the game with init. And that the right way is to use the didMove() method. So should the code be written inside here? :

override func didMove(to view: SKView) {
<#code#>
}


Does anyone know which one is the correct way? And why? Also if its wrong the way i do it, can you explain me how to use didMove method?

Don't know if this is a silly question just bothered me that using init is wrong and wanted to ask if someone knows more about this.

Answer

You should NOT override the initializers of SKScene, it's not the right place to set up you scene for several reasons

  1. the init happens way before your scene is available on the scene graph
  2. if you added children to your scene (via the Xcode scene editor) during the init the children are not available yet

You should put your code to set up the scene inside your override (after super.didMove(to:view) of

override func didMove(to view: SKView) {
    super.didMove(to: view)
    // PUT YOUR CODE HERE <-----
}

because now the scene is ready, the customisation you defined via the Xcode Scene Editor have been applied and the children have been created and added to the scene.