Skip to content
DeveloperMemos

Using SwiftUI's @StateObject

SwiftUI, StateObject, iOS Development1 min read

SwiftUI provides a variety of property wrappers that simplifies state management in our iOS applications. One such powerful property wrapper is @StateObject, which allows us to create and manage mutable state objects.

The @StateObject property wrapper is designed to be used with reference types, primarily classes. It enables us to create an observable object that persists across view updates and shares its state with multiple views. By using @StateObject, we ensure that the same instance of the object is used throughout the lifespan of the view hierarchy.

To use @StateObject, follow these steps:

  1. Create a class that conforms to the ObservableObject protocol. This class will hold the mutable state for your views. For example:
1class UserData: ObservableObject {
2 @Published var name: String = ""
3 @Published var age: Int = 0
4}
  1. In your view, declare an instance of your ObservableObject using @StateObject. For example:
1struct ContentView: View {
2 @StateObject private var userData = UserData()
3
4 var body: some View {
5 VStack {
6 Text("Name: \(userData.name)")
7 Text("Age: \(userData.age)")
8 }
9 }
10}
  1. Now, you can access and modify the state properties through the @StateObject instance in your views. Any changes to these properties will automatically update the corresponding views.
1struct ContentView: View {
2 @StateObject private var userData = UserData()
3
4 var body: some View {
5 VStack {
6 TextField("Enter Name", text: $userData.name)
7 Stepper(value: $userData.age, in: 0...100) {
8 Text("Age: \(userData.age)")
9 }
10 }
11 }
12}

By using @StateObject, you ensure that the userData object persists across view updates, and any changes to its properties trigger the necessary updates in your views. Moreover, @StateObject provides built-in memory management, releasing the object when it's no longer needed. The @StateObject property wrapper is especially useful when you need to share state among multiple views or manage complex state objects. It simplifies state management by handling all the necessary bindings and updates for you.