我一直在寻找这个问题的答案,但我找不到任何答案,类似的根本没有答案。基本上,我想用 NSKeyedUnarchiver.archiveRootObject() 保存数据并用 .unarchiveObject(withFile) 加载它。它在 Swift 2.3 上运行良好,现在它崩溃了,说非归档部分总是返回 nil。我还会检查该文件是否存在并且确实存在。我真的不知道发生了什么。这是加载过程:
func loadnotifs(_ username:String)->[AFNotificationData]{
let ArchiveURL = Constants.DocumentsDirectory.appendingPathComponent(username)
print("loading " + ArchiveURL.path)
if FileManager.default.fileExists(atPath: ArchiveURL.path) {
let unarchived = NSKeyedUnarchiver.unarchiveObject(withFile: ArchiveURL.path) as? [AFNotificationData]
if unarchived != nil {
return NSKeyedUnarchiver.unarchiveObject(withFile: ArchiveURL.path) as! [AFNotificationData]
} else {
return []
}
}
else {
return []
}
}
这是节省:
func savenotifs(_ username:String){
if username != "" {
let ArchiveURL = Constants.DocumentsDirectory.appendingPathComponent(username)
print("saving " + ArchiveURL.path)
}
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(AFDatabase.sharedDatabase.notificationList, toFile: ArchiveURL.path)
if !isSuccessfulSave {
print("Failed to save notifs")
}
}
}
但最后我总是得到“致命错误:在展开可选值时意外发现 nil”