首先,我修改了文件GameScene,将一个新的简单类MySprite作为SKSpriteNode的子类添加,以显示一个红色矩形。代码运行良好:
import SpriteKit
class MySprite: SKSpriteNode {
var scence: SKScene?
init(theParent: SKScene) {
super.init(texture: nil, color: UIColor.redColor(), size: CGSizeMake(300, 300))
self.position = CGPointMake(500, 500)
scence = theParent
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
var mySprite = MySprite(theParent: self)
self.addChild(mySprite)
}
}
然后我将该类转换为通用类,如下所示:
import SpriteKit
class MyBase {
var property: Int = 0
}
class MyGame: MyBase {
var id: Int = 0
}
class MySprite<B: MyBase>: SKSpriteNode {
var scence: SKScene?
init(theParent: SKScene) {
super.init(texture: nil, color: UIColor.redColor(), size: CGSizeMake(300, 300))
self.position = CGPointMake(500, 500)
scence = theParent // <- crash here EXC_BAD_ACCESS
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
var mySprite = MySprite<MyGame>(theParent: self)
self.addChild(mySprite)
}
}
编译好但在运行时遇到错误:在MySprite类的行scence = theParent中出现EXC_BAD_ACCESS。我已经检查过,MySprite的瞬间已经创建并且看起来很正常。
关于问题和解决方案的任何想法?非常感谢!