0
0
iOS Swiftmobile~5 mins

@StateObject for observable objects in iOS Swift

Choose your learning style9 modes available
Introduction

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

When you want to create and own a data model that changes and affects your view.
When you have a class that holds information and you want your screen to update automatically when that information changes.
When you build a screen that needs to remember and watch an object for changes during its life.
When you want to avoid creating multiple copies of the same data model in your app.
When you want SwiftUI to manage the lifetime of your data object for a view.
Syntax
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.

Examples
This example creates a counter object that the view owns and watches for changes.
iOS Swift
class Counter: ObservableObject {
  @Published var count = 0
}

struct ContentView: View {
  @StateObject var counter = Counter()
  var body: some View {
    Text("Count: \(counter.count)")
  }
}
Here, the view owns a timer model that updates the time and the view updates automatically.
iOS Swift
class TimerModel: ObservableObject {
  @Published var time = 0
}

struct ContentView: View {
  @StateObject var timer = TimerModel()
  var body: some View {
    Text("Time: \(timer.time)")
  }
}
Sample App

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.

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

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.

Summary

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