@ObservedObject helps your app watch for changes in data from outside your view. When the data changes, the view updates automatically. This keeps your app's screen fresh without you having to refresh it manually.
@ObservedObject in iOS Swift
@ObservedObject var model: YourObservableClass
The class you observe must conform to ObservableObject.
Use @Published inside the class to mark properties that trigger updates.
count changes, the text updates.class Counter: ObservableObject { @Published var count = 0 } struct ContentView: View { @ObservedObject var counter = Counter() var body: some View { Text("Count: \(counter.count)") } }
class TimerModel: ObservableObject { @Published var seconds = 0 } struct TimerView: View { @ObservedObject var timer = TimerModel() var body: some View { Text("Seconds: \(timer.seconds)") } }
This app shows a number and a button. When you tap the button, the number goes up. The view updates automatically because it watches the Counter object with @ObservedObject.
import SwiftUI class Counter: ObservableObject { @Published var count = 0 func increment() { count += 1 } } struct ContentView: View { @ObservedObject 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() } } }
Only use @ObservedObject for objects created outside the view or passed in. For objects created inside the view, use @StateObject.
Make sure your observable class uses @Published for properties you want to trigger view updates.
Views using @ObservedObject will redraw when the observed object changes.
@ObservedObject watches an external data object for changes.
When the data changes, the view updates automatically.
Use it to keep your UI in sync with your data model.