简体   繁体   English

如何使用iOS的NSCoder,NSObject和Swift 3解码Double

[英]How do I decode a Double using NSCoder, NSObject and Swift 3 for iOS

I am trying to store and load an object from persistent storage in Xcode 8.0 using Swift. 我正在尝试使用Swift从Xcode 8.0中的持久性存储中存储和加载对象。

I have followed the Start Developing iOS Apps (Swift): Jump Right In tutorial from Apple and had the same problem with the integer value for the star-rating. 我遵循了《 开始开发iOS应用程序(快速)》:在 Apple教程中向右跳转 ,对于星级的整数值也遇到了同样的问题。

This is a "cropped" version of my class 'Expense' to show the 'amount' variable which I'm having trouble with: 这是班级“费用”的“裁剪”版本,以显示我遇到问题的“金额”变量:

class Expense: NSObject, NSCoding {
    var amount: Double

    static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
    static let ArchiveURL = DocumentsDirectory.appendingPathComponent("expenses")

    struct PropertyKey {
        static let amountKey = "amount"
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(amount, forKey:PropertyKey.amountKey)
    }

    required convenience init?(coder aDecoder: NSCoder) {
        let amount = aDecoder.decodeObject(forKey: PropertyKey.amountKey) as! Double        

        self.init(date: date, amount: amount, description: description, image: image)
    }
}

When i run the simulator and it tries to load in the 'amount' i get the following exception: "fatal error: unexpectedly found nil while unwrapping an Optional value". 当我运行模拟器并尝试加载“数量”时,出现以下异常:“致命错误:在展开可选值时意外发现nil”。 I am very new to Swift and xCode and I don't really know how to fix this. 我对Swift和xCode非常陌生,我真的不知道该如何解决。

required convenience init?(coder aDecoder: NSCoder) {
    // for safety, make sure to let "amount" as optional (adding as Double?)
    let amount = aDecoder.decodeDouble(forKey:PropertyKey.amountKey) as Double?

    self.init(date: date, amount: amount, description: description, image: image)
}

Try to load the property as an optional: 尝试将属性作为可选加载:

let amount = aDecoder.decodeObject(forKey: PropertyKey.amountKey) as Double?

Also, in order to get the property from the storage you must save it first. 同样,为了从存储中获取属性,您必须先保存它。 If it is not saved yet, you should handle the case it's nil . 如果尚未保存,则应处理为nil的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM