当数据是字典时如何用 unarchivedObject 替换 NSKeyedUnarchiver.unarchiveTopLevelObjectWithData

Jor*_*n H 5 ios nskeyedunarchiver swift

iOS 16.4 已弃用unarchiveTopLevelObjectWithData(_:)并应替换为unarchivedObject(ofClass:from:).

当您归档像 一样的 Swift Dictionary 时[String: Any],如何使用较新的 API 来取消归档它?

NSKeyedUnarchiver.unarchivedObject(ofClass: [String: Any].self, from: data)导致构建时错误:

静态方法“unarchivedObject(ofClass:from:)”要求“[String : Any]”符合“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
Run Code Online (Sandbox Code Playgroud)

Han*_*ash 8

由于 Swift 字典类型[String: Any]不符合NSCoding,因此您需要返回到 using NSDictionary。由于您也使用安全编码,因此您还需要列出字典中可以包含的所有类型。

您将需要使用该unarchivedObject(ofClasses:from:)方法以便列出所有类。

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

您最终可能还需要将NSString.self和添加NSNumber.self到类列表中。继续添加错误消息中出现的类,直到它起作用为止。