This is a simple example for my case. I have a @ObservedObject viewModel (Object1), pass a property (Object2) to another view (View2) . Change value in View 2, and when i go back to View 1, i wish the value is updated too. What is the best solution?
In this Example, when i press the blue number, i wish black number is also updated. Actually I don't know why do the black number is updated after pressing button "Show". I would really appreciate if you could help me. Thanks.
import SwiftUI
import Combine
struct ContentView: View {
@ObservedObject var object1: Object1 = Object1(ob: Object2(n: 0))
@State var isShow = false
var body: some View {
NavigationView {
VStack {
Text("\(object1.object2.n)")
//NavigationLink(destination: View2(object2: object1.object2)) {
// Text("Go to view 2")
//}
View2(object2: object1.object2)
Button {
isShow = true
} label: {
Text("Show")
}.alert(isPresented: $isShow, content: {
Alert(title: Text("\(object1.object2.n)"))
})
}
}
}
}
struct View2: View {
@ObservedObject var object2: Object2
var body: some View {
Button {
object2.n += 1
} label: {
Text("\(object2.n)")
}
}
}
class Object1: ObservableObject {
@Published var object2: Object2
init(ob: Object2) {
self.object2 = ob
}
}
class Object2: ObservableObject {
@Published var n: Int = 0
init(n: Int) {
self.n = n
}
}
Here is possible solution:
Alternate is to move every
object2
dependent part into separated subview observedobject2
explicitly.