简体   繁体   中英

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.

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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