无法在NSCoding协议方法中使用惰性变量

时间:2017-04-03 06:11:39

标签: ios swift swift3 nscoding

我遇到了一个问题,我无法在init?(coder aDecoder: NSCoder)

中使用惰性变量

我的示例代码是

class Category: NSObject, NSCoding {
    var categoryID: NSInteger!
    var categoryName: String!
    var categoryLogoURL: String!
    lazy var categoryTags = [String]()
    private override init() {

    }

required init?(coder aDecoder: NSCoder) {
        self.categoryID = aDecoder.decodeInteger(forKey: "categoryID")
        self.categoryName = aDecoder.decodeObject(forKey: "categoryName") as! String
        self.categoryLogoURL = aDecoder.decodeObject(forKey: "categoryLogoURL") as! String
        self.categoryTags = aDecoder.decodeObject(forKey: "categoryTags") as! [String]
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.categoryID, forKey: "categoryID")
        aCoder.encode(categoryName, forKey: "categoryName")
        aCoder.encode(categoryLogoURL, forKey: "categoryLogoURL")
        aCoder.encode(categoryTags, forKey: "categoryTags")
    }
}

我收到错误Use of 'self' in property access 'categoryTags' before super.init initializes self

删除lazy后,一切正常。我做错了什么?

1 个答案:

答案 0 :(得分:1)

致电Super Init:

required init?(coder aDecoder: NSCoder) {
    super.init()
    self.categoryID = aDecoder.decodeInteger(forKey: "categoryID")
    self.categoryName = aDecoder.decodeObject(forKey: "categoryName") as! String
    self.categoryLogoURL = aDecoder.decodeObject(forKey: "categoryLogoURL") as! String
    self.categoryTags = aDecoder.decodeObject(forKey: "categoryTags") as! [String]
}