这是模型数据
class A {
var p: Int = 1
func update() {
self.p = self.p + 1
}
}
@Observable
class BStore: A {
// nothing
}
这是一个观点
struct ContentView: View {
@State private var bStore = BStore()
var body: some View {
CountView()
.environment(bStore)
}
}
struct CountView: View {
@Environment(BStore.self) private var bStore
var body: some View {
Text("count: \(bStore.p)")
.onTapGesture(perform: {
bStore.update()
})
}
}
bStore.p
正确更改,但不更新视图;如果class A
添加@Observable
,则视图将正常更新
我有两个问题:
-
在目前的设计和
class A
不使用@Observable
的情况下,如何使视图正确更新?如果没有,那么如何设计呢?前提是class A
不能使用@Observable
,因为class A
不仅服务于视图,@Observable class BStore
相当于class A
的代理只服务于视图 -
bStore
继承class A
并具有其所有属性和方法,并使用@Observable
,但是为什么没有跟踪bStore
的父类属性的更改,从而导致视图不更改?