@StateObject property wrapper
SwiftUI provides us with the @StateObject property wrapper which is essential for state management.
A property wrapper type that instantiates an observable object. It creates an instance for that particular view and stays alive in it or the view where you share it.
The best part about @StateObject is swift makes sure that the value will persist the value even if your view is destroyed and recreated (hence preventing crashes which occurred using @ObservaleObject).
Let’s look at an example:
class People: ObservableObject {
var name = "John"
}
Now if we want to use it inside multiple views we will inject it using the @StateObject.
struct ContentView: View {
@StateObject var person = People()
var body: some View {
Text("Name: \(person.name)")
}
}
So even if your view is updated, the Person instance will not get destroyed.
That's all!😊 Drop in your suggestions if any.
For more about @StateObject in SwiftUI I would recommend you to go through: