我想保存存儲使用UserDefaults
一個自定義的文件,但我的應用crashesh由於有問題:與存儲非財產對象
fatal error: unexpectedly found nil while unwrapping an Optional value
這裏是我的代碼,在我的自定義類,我宣佈一個空數組
class AppDefualts: NSObject {
var downloadedURLArray = [DownloadFile]() //Declare an empty array
override init() {
super.init()
downloadedURLArray = loadStoredURL()
}
//Store data
func addStored(file:DownloadFile) {
//Add URL to array and save it
downloadedURLArray.append(file)
let data = NSKeyedArchiver.archivedData(withRootObject: downloadedURLArray)
UserDefaults.standard.set(data, forKey: "storedURL")
}
//Load:
func loadStoredURL() -> Array<DownloadFile> {
let data = UserDefaults.standard.data(forKey: "storedURL")
downloadedURLArray = NSKeyedUnarchiver.unarchiveObject(with: data!) as? [DownloadFile] ?? [DownloadFile]()
return downloadedURLArray
}
任何幫助將是巨大的
編輯1: 我加NSCoding
協議:
func encode(with aCoder: NSCoder) {
aCoder.encode(downloadedURLArray, forKey: "storedURL")
}
required init?(coder aDecoder: NSCoder) {
downloadedURLArray = aDecoder.decodeObject(forKey: "storedURL") as! [DownloadFile]
}
現在應用程序崩潰是由於這樣的:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -encodeObject:forKey: cannot be sent to an abstract object of class NSCoder: Create a concrete instance!'
讀取數據存儲準則自定義對象。你試圖做的只是錯誤的。 – Desdenova