2016-10-06 41 views
0

我試圖使用Swift在Xcode 8.0中存儲和加載持久存儲中的對象。我如何使用NSCoder,NSObject和Swift 3爲iOS解碼一個Double

我遵循Apple的Start Developing iOS Apps (Swift): Jump Right In教程,並且與星級的整數值有相同的問題。

這是「裁剪」我的班「費用」,以顯示其我遇到麻煩了「量」的變化版本:

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

當我運行模擬器,它會嘗試加載在'金額'我得到以下異常:「致命錯誤:意外地發現零,同時展開一個可選值」。我對Swift和xCode非常陌生,我不知道如何解決這個問題。

+2

let amount = aDecoder.decodeDouble(forKey:PropertyKey.amountKey)as Double? 爲了安全起見,請務必讓「amount」作爲可選項(添加爲Double?) Swift 3 –

+0

其中是'必需的方便初始化函數(coder aDecoder:NSCoder){'方法結束? –

+0

@Ahmad謝謝你,工作。你可以發表你的評論作爲答案,所以我可以「接受」它:) – Frederik

回答

2
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) 
} 
+1

沒有必要說'as Double?' - 只要讓' amount'是非可選的,並且只要需要傳遞給可選參數就讓它被提升。說'雙'?不會增加任何安全性。 – Hamish

1

嘗試將財產加載作爲可選:

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

而且,爲了從存儲必須先保存它的屬性。如果尚未保存,則應處理nil