ios - NSCoding required initializer in inherited classes in Swift -


i have class foo conforms nsobject , nscoding want able persist nskeyedarchiver want create class bar, subclass of foo conform nsobject , nscoding. having problem understanding how create required convenience init?(coder adecoder: nscoder) in subclass.

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

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) \(tag)"   } } 

i can compile adding following methods on make nscoding compliant

  override func encodewithcoder(acoder: nscoder) {     acoder.encodeobject(tag, forkey: "tag")     super.encodewithcoder(acoder)   } 

this makes sense because call super.encodewithcoder(...) reusing super makes dry. problem having creating required convenience init?(...) way can seem compile 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 have copied superclass required initializer , added additional decode method subclass property. approach not seem correct...

is there better way implement this??

right after decode , assign subclass properties in required init method, call:

super.init(coder: adecoder) 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -