NSCoding : How to create required init in inherited classes

余生长醉 提交于 2019-12-08 08:26:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!