@StateObject vs. @ObservedObject: The differences explained
Article Summary
Antoine van der Lee reveals why your SwiftUI view models keep resetting unexpectedly. The culprit? Mixing up @StateObject and @ObservedObject in ways that look identical until they break.
This deep dive from SwiftLee explains the critical difference between SwiftUI's two observable property wrappers. While both connect ObservableObject models to views, choosing the wrong one causes silent bugs where state resets during view rebuilds.
Key Takeaways
- @StateObject owns the model lifetime, @ObservedObject receives it from parent
- Inline @ObservedObject creation causes unexpected resets on view updates
- iOS 17+ projects should migrate to @Observable with @State instead
- Private @StateObject clearly signals ownership in your view architecture
Use @StateObject when your view creates the model and @ObservedObject when it's injected, or risk losing state on every SwiftUI rebuild.
About This Article
SwiftUI developers lose state silently when views recreate inline @ObservedObject instances during parent updates. Counters and form data reset without warning, and the compiler doesn't catch it.
Replace @ObservedObject with @StateObject for models your view owns. If you're on iOS 17 or later, you can use the Observation framework's @Observable macro with @State instead.
There's now a clear rule: use @StateObject private var when your view creates a model, and @ObservedObject var when you receive it from elsewhere. This stops the bugs where state mysteriously resets when views rebuild.