This is a companion discussion topic for the original entry at https://www.raywenderlich.com/18272812-swiftui-fundamentals/lessons/15
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/18272812-swiftui-fundamentals/lessons/15
What is the difference between @StateObject and @ObservedObject ?
The rule is this: whichever view is the first to create your object must use @StateObject
, to tell SwiftUI it is the owner of the data and is responsible for keeping it alive. All other views must use @ObservedObject
, to tell SwiftUI they want to watch the object for changes but donโt own it directly.
Why do you use
@ObservedObject var userStore = UserStore()
instead of
@StateObject var userStore = UserStore()
?
As said on Apple Documentation
SwiftUI might create or recreate a view at any time, so itโs important that initializing a view with a given set of inputs always results in the same view. As a result, itโs unsafe to create an observed object inside a view. Instead, SwiftUI provides the
StateObject
attribute for this purpose.