NSCoding在Swift中的继承类中需要初始化器 [英] NSCoding required initializer in inherited classes in Swift
问题描述
我有类Foo,它符合 NSObject
和 NSCoding
c $ c> NSKeyedArchiver 我想创建类Bar,Foo的子类,也将符合 NSObject
和 NSCoding
。我有一个问题,了解如何在子类中创建所需的方便初始化?(coder aDecoder:NSCoder)
I have class Foo which conforms to NSObject
and NSCoding
which I want to be able to persist with NSKeyedArchiver
I want to create class Bar, a subclass of Foo that will also conform to NSObject
and NSCoding
. I am having a problem understanding how to create the required convenience init?(coder aDecoder: NSCoder)
in the subclass.
class Foo ...
so class Foo...
class Foo: NSObject, NSCoding {
let identifier:String
init(identifier:String) {
self.identifier = identifier
}
override var description:String {
return "Foo: \(identifier)"
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(identifier, forKey: "identifier")
}
required convenience init?(coder aDecoder: NSCoder) {
guard let identifier = aDecoder.decodeObjectForKey("identifier") as? String
else {
return nil
}
self.init(identifier:identifier)
}
}
然后类Bar ...
Then class Bar ...
class Bar:Foo {
let tag:String
init(identifier:String, tag:String) {
self.tag = tag
super.init(identifier: identifier)
}
override var description:String {
return "Bar: \(identifier) is \(tag)"
}
}
我可以通过添加以下方法来编译这个 NSCoding
符合
I can get this to compile by adding the following methods on to make this NSCoding
compliant
override func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(tag, forKey: "tag")
super.encodeWithCoder(aCoder)
}
这是有道理的,因为我调用 super.encodeWithCoder(...)
重用超级使这个DRY。我所遇到的问题是创建 required convenience init?(...)
唯一的方法,我似乎得到它编译是通过这样做...
this makes sense because I call super.encodeWithCoder(...)
reusing the super makes this DRY. The problem I am having is creating the required convenience init?(...)
the only way I can seem to get it to compile is by doing this...
required convenience init?(coder aDecoder:NSCoder) {
guard let identifier = aDecoder.decodeObjectForKey("identifier") as? String,
let tag = aDecoder.decodeObjectForKey("tag") as? String
else {
return nil
}
self.init(identifier:identifier, tag:tag)
}
我基本上已经复制了超类所需的初始化程序,然后为子类属性添加了额外的解码方法。这种方法似乎不正确...
I basically have copied the superclass required initializer and then added the additional decode method for the subclass property. This approach does not seem correct...
有更好的方法来实现这个?
Is there a better way to implement this??
推荐答案
我在playground尝试了代码,当我勾选错误的红色圆圈时,它只是自动添加代码。
I have try your code in playground, it just auto to add the code when I tick the red circle of the Error.
代码就像您的函数所需的方便init。
The coding is like your function required convenience init.
示例代码:
required convenience init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
这篇关于NSCoding在Swift中的继承类中需要初始化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!