70

此代码在第一个 XCode 6 Beta 上工作,但在最新的 Beta 上它不起作用并给出这样的错误Must call a designated initializer of the superclass SKSpriteNode

import SpriteKit

class Creature: SKSpriteNode {
  var isAlive:Bool = false {
    didSet {
        self.hidden = !isAlive
    }
  }
  var livingNeighbours:Int = 0

  init() {
    // throws: must call a designated initializer of the superclass SKSpriteNode
    super.init(imageNamed:"bubble") 
    self.hidden = true
  }

  init(texture: SKTexture!) {
    // throws: must call a designated initializer of the superclass SKSpriteNode
    super.init(texture: texture)
  }

  init(texture: SKTexture!, color: UIColor!, size: CGSize) {
    super.init(texture: texture, color: color, size: size)
  }
}

这就是这个类的初始化方式:

let creature = Creature()
creature.anchorPoint = CGPoint(x: 0, y: 0)
creature.position = CGPoint(x: Int(posX), y: Int(posY))
self.addChild(creature)

我坚持下去..最简单的解决方法是什么?

4

2 回答 2

95

init(texture: SKTexture!, color: UIColor!, size: CGSize)是 SKSpriteNode 类中唯一指定的初始化器,其余的都是便利初始化器,所以不能对它们调用 super。将您的代码更改为:

class Creature: SKSpriteNode {
    var isAlive:Bool = false {
        didSet {
            self.hidden = !isAlive
        }
    }
    var livingNeighbours:Int = 0

    init() {
        // super.init(imageNamed:"bubble") You can't do this because you are not calling a designated initializer.
        let texture = SKTexture(imageNamed: "bubble")
        super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
        self.hidden = true
    }

    init(texture: SKTexture!) {
        //super.init(texture: texture) You can't do this because you are not calling a designated initializer.
        super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
    }

    init(texture: SKTexture!, color: UIColor!, size: CGSize) {
        super.init(texture: texture, color: color, size: size)
    }
}

此外,我会将所有这些合并到一个初始化程序中。

于 2014-08-06T22:07:36.183 回答
13

疯狂的东西..我不完全理解我是如何设法修复它的..但这有效:

convenience init() {
    self.init(imageNamed:"bubble")
    self.hidden = true
}

init(texture: SKTexture!, color: UIColor!, size: CGSize) {
    super.init(texture: texture, color: color, size: size)
}

添加和删convenience​​除initinit(texture: SKTexture!)

于 2014-08-06T15:43:15.823 回答