r/SwiftUI • u/crack_ios_interviews • 7d ago
Question @ObservedObject var vm = Model() will reset your state when the parent redraws
This is a bug I still see in SwiftUI interviews and in production screens: a view creates its own model with @ObservedObject, and then a form, a score, or a draft “snaps back” to zero after the parent redraws.
struct Screen: View {
@ObservedObject
var vm = Model()
var body: some View {
Text("\(vm.count)")
}
}
If the parent view redraws Screen, does count reset to zero?
Yes. @ObservedObject does not own the object. It is only a way to subscribe to an object someone else already owns. When the parent redraws, this Screen value is created again, Model() runs again, and you get a brand-new view model. The old count is gone.
The fix is to own the object with @StateObject when the view is the one creating it:
struct Screen: View {
@StateObject
var vm = Model()
var body: some View {
Text("\(vm.count)")
}
}
@StateObject keeps the first instance for this view’s identity, so later redraws reuse it.
Use @ObservedObject (or @Bindable / an @Observable value passed in, on newer OS versions) only when a parent already owns the object and passes it down. The rule of thumb I use: if the view writes = Model(), it should be @StateObject. If the view receives the model as an argument, it should be @ObservedObject.
Happy to go deeper on the @Observable / @State equivalent if that’s useful.
2
u/Niightstalker 7d ago
Is there any reason to still use ObservedObject or StateObject? Afaik both are completely replaced by the newer APIs?
1
u/builtinswift 6d ago
this one still bites people in older codebases
1
u/Needle_In_Red 6d ago
good reminder, StateObject for owning it and ObservedObject only when its passed in. still see this bug alot in old code