我使用UserDefault保存字典
当我打印出UserDefault时会出现以下结果
Optional({
Hamburger = {
count = 1;
subtotal = 70;
};
Cake = {
count = 1;
subtotal = 80;
};
Steak = {
count = 1;
subtotal = 90;
};
})
我的问题是我只能删除汉堡包这样的钥匙之一吗?
保留其余两个项目
仅删除所有UserDefault,
仅删除指定的项目
答案 0 :(得分:2)
您可以从UserDefaults获取字典,然后可以删除所需的键/对象。然后可以将更新对象再次存储到UserDefault中。
let kUserDefault = UserDefaults.standard
let object = kUserDefault.object(forKey: "StoredValue") as! NSDictionary
let storedValue = NSMutableDictionary.init(dictionary:object)
storedValue.removeObject(forKey: "Hamburger")
print(storedValue)
kUserDefault.set(storedValue, forKey: "StoredValue")
kUserDefault.synchronize()
let newObject : NSMutableDictionary = kUserDefault.object(forKey: "StoredValue") as! NSMutableDictionary
print(newObject)
答案 1 :(得分:0)
找到此解决方案:
// To remove required value from dictionary
let userDefault = UserDefaults.standard
if var storedDictionary = userDefault.object(forKey: "StoredDictionary") as? [String: Any] {
storedDictionary.removeValue(forKey: "Hamburger")
userDefault.setValue(storedDictionary, forKey: "StoredDictionary")
}
// To fetch updated value again wherer you want.
if let storedDictionary = userDefault.object(forKey: "StoredDictionary") as? [String: Any] {
print("StoredDictionary: ", storedDictionary)
}