gpt4 book ai didi

swift - 将状态保存在用户默认值中

转载 作者:行者123 更新时间:2023-11-30 10:57:39 24 4
gpt4 key购买 nike

我有一个类可以保存某些东西的状态,在我的例子中是 ViewController 的一些变量,但有时它会加载错误或旧的数据,但我不明白为什么。

也许有人可以看一下我的代码,看看它是否有意义。

class TopFlopState: Codable, PersistenceState {

var group: Groups = .large {
didSet {
save()
}
}
var base: Bases = .usd {
didSet {
save()
}
}
var valueOne: StatIntervalBaseModel = StatIntervalBaseModel(stat: "ppc", interval: "24h", base: "usd") {
didSet {
save()
}
}

init(){
let savedValues = load()
if savedValues != nil {
self.group = savedValues!.group
self.base = savedValues!.base
self.valueOne = savedValues!.valueOne
}
}
}

这是 PersistenceState 协议(protocol):

/**
Saves and Loads the class, enum etc. with UserDefaults.
Has to conform to Codable.
Uses as Key, the name of the class, enum etc.

*/
protocol PersistenceState {
}


extension PersistenceState where Self: Codable {


private var keyUserDefaults: String {
return String(describing: self)
}

func save() {
saveUserDefaults(withKey: keyUserDefaults, myType: self)
}

func load() -> Self? {
return loadUserDefaults(withKey: keyUserDefaults)
}

private func saveUserDefaults<T: Codable>(withKey key: String, myType: T){
do {
let data = try PropertyListEncoder().encode(myType)
UserDefaults.standard.set(data, forKey: key)
print("Saved for Key:", key)
} catch {
print("Save Failed")
}
}

private func loadUserDefaults<T: Codable>(withKey key: String) -> T? {
guard let data = UserDefaults.standard.object(forKey: key) as? Data else { return nil }
do {
let decoded = try PropertyListDecoder().decode(T.self, from: data)
return decoded
} catch {
print("Decoding failed for key", key)
return nil
}
}
}

如果一个值被设置为它应该自动保存的值,但就像我设置的那样,有时它会保存正确的值但加载错误的值......

最佳答案

在我看来,它返回缓存。因为在 Apple official documentation ,它指出

UserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value

也许您可以更改流程、何时保存数据。在您的代码中显示您在 init() 中调用了 save() 3 次。

关于swift - 将状态保存在用户默认值中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53766341/

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