为什么 SKSpriteNode 子类在没有 encode(with:) 的情况下工作

Why does an SKSpriteNode subclass work without encode(with:)

NSCoding 协议规定:

Any object class that should be codeable must adopt the NSCoding protocol and implement its methods.

两个必需的方法是init?(coder: NSCoder)func encode(with: NSCoder)

SKSpriteNode inherits from SKNode 符合协议。当编写新的 SKSpriteNode 子类时,Xcode 的自动完成将建议以下代码以满足 NSCoding 协议要求:

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

对 super 的调用也有效:

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

为什么这段代码满足了NSCoding的要求却没有实现encode(with: NSCoder)

Xcode 只会告诉你如果你在 subclass 中编写自己指定的初始化程序而不是 encode 方法,对吗?

这是因为实际上NSCoding的要求已经在superclass、SKSpriteNode中实现了。这就是为什么您不需要实施 encode。已经继承了。

但是,初始值设定项不同。您只能在以下 rules:

下从您的 superclass 继承初始化程序

Rule 1

your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.

Rule 2

If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.

看规则1!只有当你自己没有任何指定的初始化器时,指定的初始化器才会被继承!所以通过添加这个:

init() {}

您正在向 class 添加一个指定的初始化器,这会阻止 class 自动从超级 class 继承初始化器。这就是为什么你必须添加一个 required init.