'self' used before self.init call error while using NSCoding on a custom class

强颜欢笑 提交于 2019-12-25 07:19:28

问题


I'm trying to encode a custom class so I can save it using NSKeyedArchiver.archivedDataWithRootObject

but when I try to conform to the NSCoding protocol, I get this error : 'self' used before self.init. Here is my code:

class MemberRewardsInfo: NSObject, NSCoding {
var id: Int?


  required convenience init?(coder aDecoder: NSCoder) {

    guard let unarchivedId = aDecoder.decodeObjectForKey("id") as? Int

      else {
        return nil
      } 
  }


  func encodeWithCoder(aCoder: NSCoder) {

    aCoder.encodeObject(id, forKey: "id")
  }
}

its pretty annoying, not sure why it's not working.


回答1:


The error message is sort of misleading, but you need to make init(coder:) a designated initializer.

You need to modify your init(code:) to something like this:

required init?(coder aDecoder: NSCoder) {
    guard let unarchivedId = aDecoder.decodeObjectForKey("id") as? Int else {
            return nil
    }
    self.id = unarchivedId
    super.init()
}



回答2:


Apparently it's upset about convenience. The assumption is that if you create a convenience initializer, it's going to chain to a "real initializer.




回答3:


When using a convenience initializer, just call the designated initializer, in your case, self.init(), inside block. See this example in Apple docs for an explanation.

required convenience init?(coder aDecoder: NSCoder) {
    guard let unarchivedId = aDecoder.decodeObjectForKey("id") as? Int

    else {
        return nil
    }
    self.init()
    self.id = unarchivedId

}



来源:https://stackoverflow.com/questions/38881755/self-used-before-self-init-call-error-while-using-nscoding-on-a-custom-class

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