【问题标题】:NSCoding : Found nil unwrapping an Optional valueNSCoding : 发现 nil 展开一个可选值
【发布时间】:2016-10-13 15:18:27
【问题描述】:

自从更新到 Swift 3 后,我遇到了这个我自己无法解决的众所周知的崩溃……:

致命错误:在展开可选值时意外发现 nil*:

上线

self.isDefault = aDecoder.decodeObject(forKey: "BoxUserDefault_isDefault") as! Bool

为什么现在会崩溃?

这是我的课

class BoxUserDefault: NSObject, NSCoding {

    var frendlyName: String
    var hostname: String
    var isDefault: Bool

    init(frendlyName: String, hostname: String, isDefault: Bool) {
        self.frendlyName = frendlyName
        self.hostname = hostname
        self.isDefault = isDefault
        super.init()
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.frendlyName, forKey: "BoxUserDefault_frendlyName")
        aCoder.encode(self.hostname, forKey: "BoxUserDefault_hostname")
        aCoder.encode(self.isDefault, forKey: "BoxUserDefault_isDefault")
    }

    required init?(coder aDecoder: NSCoder) {
        self.frendlyName = aDecoder.decodeObject(forKey: "BoxUserDefault_frendlyName") as! String
        self.hostname = aDecoder.decodeObject(forKey: "BoxUserDefault_hostname") as! String
        self.isDefault = aDecoder.decodeObject(forKey: "BoxUserDefault_isDefault") as! Bool

        super.init()
    }
}

有什么想法吗?谢谢大家

【问题讨论】:

    标签: swift nscoding


    【解决方案1】:

    使用适当的方法decodeBool(forKey:

    self.isDefault = aDecoder.decodeBool(forKey: "BoxUserDefault_isDefault")!
    

    【讨论】:

    • 看起来工作正常!感觉很蠢^^谢谢队友
    猜你喜欢
    • 1970-01-01
    • 2016-06-17
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多