NSCoding:发现 nil 展开一个可选值

NSCoding : Found nil unwrapping an Optional value

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

fatal error: unexpectedly found nil while unwrapping an Optional value* :

在线

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

为什么现在会崩溃?

这是我的 class

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

有什么想法吗?谢谢大家

使用合适的方法decodeBool(forKey:

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