Sample code shown in video uses @State instead of @StateObject?

At min 21 into the video Bring Core Data concurrency to Swift and SwiftUI, Scott entered

@State private var selectedSort = SelectedSort()

Why is he not using @StateObject? I would have expected @StateObject is the way to go here as we are creating the SelectedSort() within the View. Because we want to tell SwiftUI to reserve storage for this property and keep it across view updates.

I would expect that using @State would mean that our SelectedSort() is re-created whenever the View is re-created, with the effect that sorting reverts to default.

What is the correct way to do it and why?

Answered by Procrastin8 in 678304022

Haven't watched the session yet but if it's a value type, @State is correct and it wont get regenerated on each init or each body call. If it's an ObservableObject, then you'd be correct in choosing @StateObject (or @ObservedObject if someone outside of the SwiftUI view hierarchy owns the object.)

Accepted Answer

Haven't watched the session yet but if it's a value type, @State is correct and it wont get regenerated on each init or each body call. If it's an ObservableObject, then you'd be correct in choosing @StateObject (or @ObservedObject if someone outside of the SwiftUI view hierarchy owns the object.)

Sample code shown in video uses @State instead of @StateObject?
 
 
Q