我创建了一个这样的模型:
class TestModel: ObservableObject {
@Published var num: Int = 0
}
模型用于“主页”视图和“主页”的子视图“HomeSub”
struct Home: View {
@StateObject var model = TestModel()
var body: some View {
NavigationView(content: {
NavigationLink(destination: HomeSub(model: model)) { Text("\(model.num)") }
})
}
}
struct HomeSub: View {
//1
@StateObject var model = TestModel()
//2
@ObservedObject var model = TestModel()
var body: some View {
VStack {
Text("\(model.num)")
.padding()
.background(Color.red)
Button("Add") {
model.num += 1
}
}
.onChange(of: model.num, perform: { value in
print("homeSub: \(value)")
})
}
}
在 HomeSub 视图中,1 和 2 有什么区别?当我运行该项目时,它们的行为完全相同。