1. 发生问题的demo
业务逻辑代码
class Address: ObservableObject {
@Published var street = "123 Apple Street"
@Published var city = "Cupertino"
}
class User: ObservableObject {
@Published var name = "Tim Cook"
@Published var address = Address()
}
struct ContentView: View {
@ObservedObject var user = User()
var body: some View {
VStack {
Text("Name: \(user.name)")
Text("Address: \(user.address.street), \(user.address.city)")
Button("Change Address") {
user.address.street = "New York"
}
}
}
}
当我有一个嵌套的ObservedObject时,嵌套对象的已发布属性的更改不会更新UI,直到父对象发生变化,才会刷新。
2. 修改后的代码
SwiftUI(更准确地说是Combine)只能看到值的变化,因此,它可以看到@Published结构实例的属性值的变化,而不能看到@Published类。
如果您希望基于这些嵌套对象的属性值的更改来更新Ul,则使用嵌套对象的结构实例。如果必须使用类实例,请使用另一种机制显式地通知更改。下面是使用struct代替class的NestedObject修改的代码
业务逻辑代码
struct Address {
var street = "123 Apple Street"
var city = "Cupertino"
}
class User: ObservableObject {
@Published var name = "Tim Cook"
@Published var address = Address()
}
struct ContentView: View {
@ObservedObject var user = User()
var body: some View {
VStack {
Text("Name: \(user.name)")
Text("Address: \(user.address.street), \(user.address.city)")
Button("Change Address") {
user.address.street = "New York"
}
}
}
}
总结一句话,一个对象只需要当前属性@Published就可以了,子类使用struct