@StateObject helps you keep track of data that can change over time in your app. It makes sure your screen updates when the data changes.
@StateObject for observable objects in iOS Swift
@StateObject var model = MyObservableModel()
Use @StateObject only once per observable object in a view to create and own it.
Use classes that conform to ObservableObject with @Published properties inside.
class Counter: ObservableObject { @Published var count = 0 } struct ContentView: View { @StateObject var counter = Counter() var body: some View { Text("Count: \(counter.count)") } }
class TimerModel: ObservableObject { @Published var time = 0 } struct ContentView: View { @StateObject var timer = TimerModel() var body: some View { Text("Time: \(timer.time)") } }
This app shows a number that starts at zero. When you tap the button, the number goes up by one. The view updates automatically because it watches the counter object using @StateObject.
import SwiftUI class Counter: ObservableObject { @Published var count = 0 func increment() { count += 1 } } struct ContentView: View { @StateObject var counter = Counter() var body: some View { VStack(spacing: 20) { Text("Count: \(counter.count)") .font(.largeTitle) Button("Increment") { counter.increment() } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .padding() } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
Do not use @StateObject for objects passed from parent views; use @ObservedObject instead.
@StateObject creates and owns the object, so it stays alive as long as the view does.
Always mark your data class with ObservableObject and properties with @Published to notify changes.
@StateObject creates and owns an observable object in a SwiftUI view.
It makes the view update automatically when the data changes.
Use it once per object in the view that owns the data.