我想在不使用 Codable 的情况下将对象数组保存在用户默认值中。
我尝试将它转换为数据中的数组并保存在用户默认值中:
let childsArray = result["childs"] as? [[String: Any]]
let childsData = NSKeyedArchiver.archivedData(withRootObject: childsArray!)
UserDefaults.standard.set(childsData, forKey: "childsArray")
UserDefaults.standard.synchronize()
它给了我这个警告:
'archivedData(withRootObject:)' was deprecated in iOS 12.0: Use +archivedDataWithRootObject:requiringSecureCoding:error: instead
如何解决此警告并实现在 UserDefaults 中保存对象数组的预期目标?
最佳答案
您可以使用以下代码归档数组:
do {
let childsData = try NSKeyedArchiver.archivedData(withRootObject: childsArray!, requiringSecureCoding: true)
UserDefaults.standard.set(childsData, forKey: "childsArray")
UserDefaults.standard.synchronize()
} catch {
print(error)
}
并使用以下代码取消归档对象:
do {
let childData = UserDefaults.standard.value(forKey: "childsArray")
if let childArray = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(childData as! Data) {
print(childArray)
}
} catch {
print(error)
}
关于ios - 如何在 iOS 12.0 的 UserDefaults 中保存对象数组。使用任何数组 [[String : Any]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54123466/