gpt4 book ai didi

swift3 - NSKeyedArchiver.unarchiveObject Swift 3 iOS 10

转载 作者:行者123 更新时间:2023-12-01 18:30:15 25 4
gpt4 key购买 nike

我一直在寻找这个问题的答案,但我找不到任何答案,类似的问题根本没有答案。基本上,我想使用 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")
}

}
}

但最后我总是得到“ fatal error :在解包可选值时意外发现 nil”

最佳答案

我找错地方了。其实保存和加载过程都很好,问题是需要遵守 NSCoding 协议(protocol)所需的 init:我正在使用

aDecoder.decodeObject(forKey:xxx) as! Bool

而不是新的

aDecoder.decodeBool(forKey:xxx)

事实上,它是由 swift 2.3->3 转换器使用错误的命令自动更改的,请注意这一点!

此外,请注意,因为此命令与 swift 2.3 中的 bool 值/整数不兼容。

关于swift3 - NSKeyedArchiver.unarchiveObject Swift 3 iOS 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39830142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com