SwiftUI Data Flow @ObservedObject & @StateObject
SwiftUI Data Flow: @ObservedObject & @StateObject
Use ObservableObject with @StateObject to own the model and @ObservedObject to observe it from child views.
StateObject
Render a counter that increments when the button is pressed.
Example
import SwiftUI
class CounterModel: ObservableObject {
@Published var count = 0
}
struct Child: View {
@ObservedObject var model: CounterModel
var body: some View {
HStack {
Text("Count: \(model.count)")
Button("+1") { model.count += 1 }
}
}
}
struct Parent: View {
@StateObject private var model = CounterModel()
var body: some View {
Child(model: model)
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { Parent() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
The example above shows a counter that increments when the button is pressed.