【问题标题】:Could not use lazy variable inside NSCoding protocol methods无法在 NSCoding 协议方法中使用惰性变量
【发布时间】:2017-04-03 06:11:39
【问题描述】:

我遇到了一个问题,我无法在 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,一切正常。我做错了什么?

【问题讨论】:

    标签: ios swift swift3 nscoding


    【解决方案1】:

    调用超级初始化:

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

    【讨论】:

    • 它已修复。您能解释一下为什么在使用惰性变量时需要使用“super.init()”来调用它吗?
    • 期待它!这是本能的。
    • @Sree 你找到原因了吗?
    • @Bista 尚未找到 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    相关资源
    最近更新 更多