DevPrep

All topics › SwiftUI

How does @StateObject differ from @ObservedObject in practice?

Middle PRO

The gist (pre-iOS 17 API, ObservableObject)

@StateObject creates the object once for the view's lifetime and keeps it in SwiftUI's storage, so it survives any re-evaluation of the parent's body. @ObservedObject only subscribes the view to an object someone passed in; if you create it inside the view, then every time the parent rebuilds that view the object is created again and its state is lost.

Rule: whoever owns — @StateObject; whoever receives — @ObservedObject.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store