Observable Objects | raywenderlich.com


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 ?

article

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.