如何使用 NSCoder、NSObject 和 Swift 3 for iOS 解码 Double [英] How do I decode a Double using NSCoder, NSObject and Swift 3 for iOS

查看:34
本文介绍了如何使用 NSCoder、NSObject 和 Swift 3 for iOS 解码 Double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Swift 从 Xcode 8.0 中的持久存储中存储和加载对象.

I am trying to store and load an object from persistent storage in Xcode 8.0 using Swift.

我遵循了开始开发 iOS 应用程序 (Swift):直接进入 来自 Apple 的教程,对于星级的整数值也有同样的问题.

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.

这是我的类费用"的裁剪"版本,用于显示我遇到问题的金额"变量:

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

当我运行模拟器并尝试加载数量"时,我收到以下异常:致命错误:在解开可选值时意外发现 nil".我对 Swift 和 xCode 非常陌生,我真的不知道如何解决这个问题.

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". I am very new to Swift and xCode and I don't really know how to fix this.

推荐答案

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

这篇关于如何使用 NSCoder、NSObject 和 Swift 3 for iOS 解码 Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆