Swift3 NSKeyedArchiver.unarchiveObject Swift 3 iOS 10
我一直在寻找这个问题的答案,但我找不到任何答案,类似的问题根本没有答案。 基本上,我想用NSKeyedUnarchiver.archiveRootObject()保存数据,然后用.unarchiveObject(withFile)加载数据。Swift 2.3运行良好,现在它崩溃了,说非归档部分总是返回零。我还检查文件是否存在,它是否存在。我真的不知道发生了什么事。 这是加载程序:Swift3 NSKeyedArchiver.unarchiveObject Swift 3 iOS 10,swift3,ios10,nskeyedunarchiver,Swift3,Ios10,Nskeyedunarchiver,我一直在寻找这个问题的答案,但我找不到任何答案,类似的问题根本没有答案。 基本上,我想用NSKeyedUnarchiver.archiveRootObject()保存数据,然后用.unarchiveObject(withFile)加载数据。Swift 2.3运行良好,现在它崩溃了,说非归档部分总是返回零。我还检查文件是否存在,它是否存在。我真的不知道发生了什么事。 这是加载程序: func loadnotifs(_ username:String)->[AFNotificationData
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”我找错了地方。实际上,保存和加载过程很好,问题在于遵守NSCoding协议所需的init: 我在用
aDecoder.decodeObject(forKey:xxx) as! Bool
而不是新的
aDecoder.decodeBool(forKey:xxx)
鉴于swift 2.3->3转换器使用错误的命令自动更改,请注意
此外,请注意,因为此命令与swift 2.3中的布尔/整数不兼容