如何在 iOS 12.0 的 UserDefaults 中保存对象数组。使用任何数组 [[String: Any]]
How to Save Array of object in UserDefaults in iOS 12.0. using Any Array [[String: Any]]
我想在不使用 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 中保存对象数组的预期目标?
let object1 = ["key1":"value1"]
let object2 = ["key2":"value2"]
let array = [object1, object2]
UserDefaults.standard.set(array, forKey: "childArray")
UserDefaults.standard.synchronize()
let storedArray = UserDefaults.standard.value(forKey: "childArray") as! [[String:String]]
print(storedArray)
您可以使用以下代码归档数组:
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)
}
我想在不使用 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 中保存对象数组的预期目标?
let object1 = ["key1":"value1"]
let object2 = ["key2":"value2"]
let array = [object1, object2]
UserDefaults.standard.set(array, forKey: "childArray")
UserDefaults.standard.synchronize()
let storedArray = UserDefaults.standard.value(forKey: "childArray") as! [[String:String]]
print(storedArray)
您可以使用以下代码归档数组:
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)
}