0
0
iOS Swiftmobile~5 mins

@ObservedObject in iOS Swift

Choose your learning style9 modes available
Introduction

@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.

You want a view to update when data changes in a separate object.
You have a shared data model that multiple views need to watch.
You want to keep your data logic separate from your view code.
You want to react to changes in data that come from network or user input.
You want to build a simple app that updates UI automatically when data changes.
Syntax
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.

Examples
This example shows a simple counter class and a view that watches it. When count changes, the text updates.
iOS Swift
class Counter: ObservableObject {
  @Published var count = 0
}

struct ContentView: View {
  @ObservedObject var counter = Counter()

  var body: some View {
    Text("Count: \(counter.count)")
  }
}
This example shows a timer model and a view that updates the seconds display automatically.
iOS Swift
class TimerModel: ObservableObject {
  @Published var seconds = 0
}

struct TimerView: View {
  @ObservedObject var timer = TimerModel()

  var body: some View {
    Text("Seconds: \(timer.seconds)")
  }
}
Sample App

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.

iOS Swift
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()
    }
  }
}
OutputSuccess
Important Notes

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.

Summary

@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.