Thibault B.
Thibault B.

Reputation: 108

NSCoding : How to create required init in inherited classes

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)

Upvotes: 1

Views: 1705

Answers (2)

RYANCOAL9999
RYANCOAL9999

Reputation: 47

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")

}

Upvotes: -1

Ahmed Onawale
Ahmed Onawale

Reputation: 4050

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)
  }

}

Upvotes: 2

Related Questions