0
0
iOS Swiftmobile~5 mins

ObservableObject protocol in iOS Swift

Choose your learning style9 modes available
Introduction

The ObservableObject protocol helps your app watch for changes in data. When data changes, the app updates the screen automatically.

You want to update the user interface when data changes.
You have a shared data model used by many views.
You want to keep your code clean by separating data from UI.
You want to react to user input and show changes immediately.
Syntax
iOS Swift
class MyModel: ObservableObject {
  @Published var someData: String = ""
}

Use class because ObservableObject works only with classes.

Mark properties with @Published to notify views when they change.

Examples
A simple counter that updates views when count changes.
iOS Swift
class Counter: ObservableObject {
  @Published var count = 0
}
Tracks user info and login state, updating UI when these change.
iOS Swift
class UserSettings: ObservableObject {
  @Published var username = "Guest"
  @Published var isLoggedIn = false
}
Sample App

This app shows a number and a button. When you tap the button, the number goes up. The screen updates automatically because Counter uses ObservableObject and @Published.

iOS Swift
import SwiftUI

class Counter: ObservableObject {
  @Published var count = 0
}

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

  var body: some View {
    VStack(spacing: 20) {
      Text("Count: \(counter.count)")
        .font(.largeTitle)
      Button("Increment") {
        counter.count += 1
      }
      .padding()
      .background(Color.blue)
      .foregroundColor(.white)
      .cornerRadius(8)
    }
    .padding()
  }
}

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}
OutputSuccess
Important Notes

Always use @StateObject in views to create and own an ObservableObject.

Use @ObservedObject when a view receives an ObservableObject from elsewhere.

Remember, only classes can conform to ObservableObject, not structs.

Summary

ObservableObject lets your app watch data changes and update UI automatically.

Mark changing properties with @Published to notify views.

Use @StateObject or @ObservedObject in views to connect data and UI.