@StateObject vs @ObservedObject in SwiftUI

Swapnanil Dhol
2 min readJun 26, 2020

--

At WWDC 2020 SwiftUI got a new property wrapper called @StateObject. What is the main purpose and why does this new property wrapper exist?

Previously when views subscribed to Data models, they did so with the @ObservedObject property wrapper. This was fine, however there was a critical issue.
@ObservedObject is not owned by the view. It is not considered to be the view’s ultimate source of truth. The variable attached to the said property wrapper is not in control/dependent on the view’s lifecycle. This caused an error especially when a view would instantiate its body property before the @ObservedObject property could be initialized and therefore could result in a crash. Since views in SwiftUI are super cheap to create, the framework can and will regularly destroy and create a new view (especially when the Source Of Truth changes its data) and during this process, if the @ObservedObject property wasn’t initialized, the view along with the app will crash since it doesn’t have its source of truth (i.e. its data)

The Solution

To solve this, Apple introduced @StateObject. @StateObject does pretty much the same thing as @ObservedObject however this property is owned by the view and it will execute right before the body property of the view is instantiated.
Since this property is owned by the view, it is dependent on the view’s lifecycle so when the view is created you’ll have the peace of mind to know for sure that your DataModel is accessible by the view. @StateObjectties an ObservableObject to a view’s lifecycle and it’s meant to be your view’s ultimate source of truth.

All you have to do to adapt @StateObject in your projects is to change the existing @ObservedObjectwrapped properties with @StateObject. That’s it!

--

--

Swapnanil Dhol
Swapnanil Dhol

Written by Swapnanil Dhol

•23 • 3x WWDC Scholar •GSoC 2020 with VLC •iOS Engineer •Airplane and Space Enthusiast

No responses yet