首页 文章

NSCoding:发现nil展开一个Optional值

提问于
浏览
2

自从更新到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()
    }
}

任何的想法 ?多谢你们

1 回答

  • 7

    使用适当的方法 decodeBool(forKey:

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

相关问题