Junior — Middle
What is the difference between the StateObject and ObservableObject classes in the context of state management?
sobes.tech AI
Answer from AI
In SwiftUI, ObservableObject and StateObject are related to state management but serve different roles:
-
ObservableObject is a protocol that a class must conform to so that its changes can be observed in SwiftUI. A class conforming to this protocol publishes changes via its
@Publishedproperty. -
StateObject is a property wrapper used in views to create and store an instance of a class conforming to
ObservableObject. It ensures that the object is created once and persists across view updates.
Example:
class ViewModel: ObservableObject {
@Published var count = 0
}
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
VStack {
Text("Count: \(viewModel.count)")
Button("Increment") {
viewModel.count += 1
}
}
}
}
Here, ViewModel is a class with state, and @StateObject in ContentView is responsible for its creation and storage.