我将代码从UserDefaults更改为新的@AppStorage。
我读到在没有定义suiteName für @AppStorage的情况下它将使用UserDefaults.standard。在我的例子中,这似乎不起作用:
我可以使用这个getLastContactDownload()函数从UserDefaults.standard获取日期:
struct Defaults {
private static let userDefault = UserDefaults.standard
static func getLastContactDownload() -> Date {
return userDefault.object(forKey: "lastContactDownload") as? Date ?? Date(timeIntervalSinceNow: -365 * 24 * 60 * 60)
}
}我用setLastContactDownload()函数给它保存了一个值:
static func setLastContactDownload(_ lastContactDownload: Date) {
userDefault.set(lastContactDownload, forKey: "lastContactDownload")
}在我的视图中,我现在使用新的@AppStorage:
@AppStorage("lastContactDownload") var lastContactDownload: Date = Date(timeIntervalSinceNow: -365 * 24 * 60 * 60)现在我希望,这会给我相同的日期:
.onAppear {
print(lastContactDownload)
print(Defaults.getLastContactDownload())
}但事实并非如此。
控制台打印:
2020-02-18 10:21:22 +0000
2021-02-17 10:09:02 +0000@AppStorage "lastContactDownload“似乎为空,并打印我定义的默认值(过去一年)。
使用lastContactDownload = Date()以新的@AppStorage方式保存和读取变量将会起作用,但我的目标是,为什么它不使用与旧方式相同的UserDefaults.standard (我想在将代码更改为@AppStorage时保留这些值)?
发布于 2021-02-17 19:34:58
我现在发现的是:
这似乎是一个模拟器错误。如果我在一个真实的设备上执行相同的代码,我会打印出相同的日期。
https://stackoverflow.com/questions/66240209
复制相似问题