@StateObject

Could you please make a
comparison with @ObservedObject ?
thanks

Replies

@ObservedObject basically indicates your view's desire to observe some reference type that conforms to ObservableObject. It's sole purpose is to indicate to SwiftUI that you want your view updated when changes are detected on the object that is being observed.

@StateObject does that as well, but, and this is very important, also controls the lifetime of the @ObservedObject. This means that a property marked with @StateObject will get instantiated and destroyed only when appropriate. @StateObject properties don't get destroyed and re-instantiated every time their containing view struct goes in and out of scope (just like @State). By comparison, @ObservedObject makes no such guarantees.

You can use instances created with @StateObject directly in the view that declares them itself, or pass them down the hierarchy in @ObservedObject properties or in the environment via @EnvironmentObject property and .environmentObject modifier pair.
So do you recommand to use StateObject everytime instead of ObservedObject?
Or is there some scenarios where ObservedObject remains useful?
I found this article very helpful. It states also when not use StateObject.
donnywals.com/whats-the-difference-between-stateobject-and-observedobject/


For additional information on how to use these property wrappers, please also see Managing Model Data in Your App.
How might one extend an existing reference type, say SCNScene, to conform to ObservableObject?