ios 当数据是字典时,如何将NSKeyedUnarchiver.unarchiveTopLevelObjectWithData替换为unarchivedObject

mepcadol  于 2023-03-05  发布在  iOS
关注(0)|答案(1)|浏览(286)

iOS 16.4已弃用unarchiveTopLevelObjectWithData(_:),应替换为unarchivedObject(ofClass:from:)
当您归档Swift Dictionary(如[String: Any])时,如何使用更新的API来取消归档?
NSKeyedUnarchiver.unarchivedObject(ofClass: [String: Any].self, from: data)导致生成时错误:
静态方法“unarchivedObject(ofClass:from:)”要求"[字符串:任何]'符合'NSCoding'

//create the data from dictionary
let dictionary: [String: Any] = ["Text": "Hello", "Number": 1, "Array": ["Hello", "World"]]
let data = try! NSKeyedArchiver.archivedData(withRootObject: dictionary, requiringSecureCoding: true)

//and later get the dictionary from the data
let dictionary = try? NSKeyedUnarchiver.unarchivedObject(ofClass: [String: Any].self, from: data) //sorry no can do
2vuwiymt

2vuwiymt1#

由于[String: Any]类型的Swift字典不符合NSCoding,因此需要重新使用NSDictionary,由于还使用了安全编码,因此还需要列出字典中可能存在的所有类型。
您需要使用unarchivedObject(ofClasses:from:)方法,以便列出所有类。

let dictionary = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSDictionary.self, NSArray.self], from: data) as? NSDictionary

您可能还需要将NSString.selfNSNumber.self添加到类列表中,请继续添加错误消息中显示的类,直到它工作为止。

相关问题