Sobes.tech
Middle

What is state, state object, and observed object in iOS development?

sobes.tech AI

Answer from AI

State — a property wrapper in SwiftUI that allows managing local view state. When the value of a property wrapped in @State changes, the view automatically updates.

StateObject — a property wrapper in SwiftUI for creating and managing objects conforming to the ObservableObject protocol, which are part of the view's lifecycle. It is effective for objects created inside the view and living with it.

ObservedObject — a property wrapper in SwiftUI for managing references to existing objects conforming to the ObservableObject protocol, which are passed from outside. SwiftUI monitors changes in these objects and updates the view.

Comparison table:

Wrapper Purpose Ownership Example usage
@State Local view state View Simple counter, visibility flag
@StateObject Creating and owning an ObservableObject View View model (ViewModel) created within the view
@ObservedObject Tracking an ObservableObject passed from outside External source View model (ViewModel) passed from a parent view

Example of using @State:

struct CounterView: View {
    @State private var count: Int = 0 // Local state

    var body: some View {
        VStack {
            Text("Count: \(count)")
            Button("Increment") {
                count += 1 // Changing state triggers update
            }
        }
    }
}

Example of using @StateObject and @ObservedObject:

import SwiftUI

// ObservableObject for data model
class DataModel: ObservableObject {
    @Published var value: String
    
    init(value: String) {
        self.value = value
    }
}

struct ContentView: View {
    // Create and own an instance of DataModel
    @StateObject private var localData = DataModel(value: "Initial Local Value")

    var body: some View {
        VStack {
            Text("Local Data: \(localData.value)")
            Button("Change Local Data") {
                localData.value = "Changed Local Value \(Int.random(in: 1...100))"
            }
            
            // Pass localData to a child view
            ChildView(observedData: localData)
        }
    }
}

struct ChildView: View {
    // Observe the DataModel instance passed from the parent
    @ObservedObject var observedData: DataModel

    var body: some View {
        VStack {
            Text("Observed Data in Child: \(observedData.value)")
            Button("Change Observed Data") {
                observedData.value = "Changed from Child \(Int.random(in: 1...100))"
            }
        }
    }
}
What is state, state object, and observed object in… - sobes.tech