【问题标题】:'self' used before self.init call error while using NSCoding on a custom class在自定义类上使用 NSCoding 时,在 self.init 调用错误之前使用了“self”
【发布时间】:2016-08-10 19:13:46
【问题描述】:

我正在尝试对自定义类进行编码,以便可以使用 NSKeyedArchiver.archivedDataWithRootObject 保存它

但是当我尝试遵循 NSCoding 协议时,我得到了这个错误:'self' used before self.init。这是我的代码:

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

这很烦人,不知道为什么它不起作用。

【问题讨论】:

    标签: ios swift nscoding nscoder


    【解决方案1】:

    错误消息有点误导,但您需要将 init(coder:) 指定为指定的初始化程序。

    您需要将您的init(code:) 修改为如下内容:

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

    【讨论】:

      【解决方案2】:

      显然它对convenience 感到不安。假设是,如果您创建一个便利初始化程序,它将链接到一个“真正的初始化程序”。

      【讨论】:

        【解决方案3】:

        当使用便利初始化器时,只需调用指定的初始化器,在你的例子中,self.init(),在块内。有关说明,请参阅 Apple 文档中的 this example

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

        }

        【讨论】:

          猜你喜欢
          • 2019-09-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多