如何使用 NSCoder、NSObject 和 Swift 3 为 iOS 解码 Double
How do I decode a Double using NSCoder, NSObject and Swift 3 for iOS
我正在尝试使用 Swift.
在 Xcode 8.0 中从持久存储中存储和加载对象
我已按照 Apple 的 Start Developing iOS Apps (Swift): Jump Right In 教程进行操作,但在星级评分的整数值方面遇到了同样的问题。
这是我的 class 'Expense' 的 "cropped" 版本,用于显示我遇到问题的 'amount' 变量:
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)
}
}
当我 运行 模拟器并尝试在 'amount' 中加载时,我得到以下异常:"fatal error: unexpectedly found nil while unwrapping an Optional value"。我是 Swift 和 xCode 的新手,我真的不知道如何解决这个问题。
尝试将 属性 作为可选项加载:
let amount = aDecoder.decodeObject(forKey: PropertyKey.amountKey) as Double?
此外,为了从存储中获取 属性,您必须先保存它。如果还没有保存,你应该处理 nil
.
的情况
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)
}
我正在尝试使用 Swift.
在 Xcode 8.0 中从持久存储中存储和加载对象我已按照 Apple 的 Start Developing iOS Apps (Swift): Jump Right In 教程进行操作,但在星级评分的整数值方面遇到了同样的问题。
这是我的 class 'Expense' 的 "cropped" 版本,用于显示我遇到问题的 'amount' 变量:
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)
}
}
当我 运行 模拟器并尝试在 'amount' 中加载时,我得到以下异常:"fatal error: unexpectedly found nil while unwrapping an Optional value"。我是 Swift 和 xCode 的新手,我真的不知道如何解决这个问题。
尝试将 属性 作为可选项加载:
let amount = aDecoder.decodeObject(forKey: PropertyKey.amountKey) as Double?
此外,为了从存储中获取 属性,您必须先保存它。如果还没有保存,你应该处理 nil
.
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)
}