问题
I have the same question as vince (NSCoding required initializer in inherited classes in Swift)
I've a class 'Source' and a subclass 'RSSSource'. Theses classes conforms to NSObject
and NSCoding
which I want to be able to persist with NSKeyedArchiver
.
I don't know how to create the required convenience init?(coder aDecoder: NSCoder)
in the subclass. I would like to call the convenience init
of the superclass.
PS: I know that I should post a comment on his thread but I can't. (reputation too low)
回答1:
Here is a simple example:
class Source: NSObject, NSCoding {
var name: String?
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObjectForKey("name") as? String
}
}
class RSSSource: Source {
var rssName: String?
override func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "rssName")
super.encodeWithCoder(aCoder)
}
required init?(coder aDecoder: NSCoder) {
rssName = aDecoder.decodeObjectForKey("rssName") as? String
super.init(coder: aDecoder)
}
}
回答2:
I have try the it, it just auto add the coding. You don't need to add the your coding by yourself otherwise you want to change.
sample coding:
required convenience init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
来源:https://stackoverflow.com/questions/35865947/nscoding-how-to-create-required-init-in-inherited-classes