即使已连接并运行,它似乎也不存储值,这是代码:
文件1
struct ContentView: View {
@ObservedObject var eatTracker = TimeToEatTrackerViewModel()
var body: some View {
VStack(spacing: 30) {
Button(action: {
self.eatTracker.currentMeal += 1
print(String(self.eatTracker.currentMeal))
}){
Text("Who's next?")
}
}
}
}
文件2
class TimeToEatTrackerViewModel: ObservableObject {
@Published var currentMeal: Int = UserDefaults.standard.integer(forKey: "CurrentMeal") {
didSet {
UserDefaults.standard.set(self.currentMeal, forKey: "CurrentMeal")
}
}
}
如果我在与@State
的同一个文件上执行此操作,那么它可以工作,但是像这样对我不起作用,为什么?
非常感谢
答案 0 :(得分:0)
尝试一下:
self.eatTracker.currentMeal = self.eatTracker.currentMeal + 1
代替:
self.eatTracker.currentMeal += 1