gpt4 book ai didi

swift - 我应该如何从 UserDefaults 更新对象值?

转载 作者:可可西里 更新时间:2023-11-01 01:06:54 25 4
gpt4 key购买 nike

有如下结构

struct User:Codable {
static var shared = User()
var name:String!
var age:Int!
}

用户可以保存他们的信息

var userInfo = User.shared
userInfo.name = "Kevin"
userInfo.age = 28
UserDefaults.standard.set(try? PropertyListEncoder().encode(userInfo), forKey:"UserInformation")

下面我试过了

但它似乎创建了新对象

UserDefaults.standard.set(try? PropertyListEncoder().encode(userInfo.age == 32), forKey:"UserInformation")

是否可以只从 UserDefault 更新 userInfo 对象?

喜欢只改变userInfo.age = 32

最佳答案

你需要解码对象,改变它的值,然后再编码回来:

guard let data = UserDefaults.standard.data(forKey: "UserInformation") else {
// no data associated with the key!
}
guard var obj = try? PropertyListDecoder().decode(User.self, from: data) else {
// something wrong happened with decoding
}
obj.age = 32 // changing the object...
guard let newData = try? PropertyListEncoder().encode(obj) else {
// something wrong happened with encoding
}
UserDefaults.standard.set(newData, forKey: "UserInformation")

关于swift - 我应该如何从 UserDefaults 更新对象值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57753944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com