@StateObject vs @ObservedObject in SwiftUI

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

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

•20 • WWDC ’19, ’20 Scholar •GSoC 2020 with VLC •iOS Engineer • @neontheapp •Airplane and Space Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store