In SwiftUI, why does a feed view model declared with @ObservedObject reset whenever the parent tab redraws, and how does @StateObject fix it?
answer
- view structs are rebuilt often
- owner versus borrower
- default value runs again
- autoclosure evaluated once per identity
basics
~20 s@ObservedObject does not own its object, so a default value like FeedViewModel() runs again whenever the parent rebuilds the view struct. @StateObject owns it: SwiftUI creates the model once per view identity and keeps it across redraws.
solid answer
~40 sA SwiftUI view is a struct the parent rebuilds every time its `body` runs. With `@ObservedObject var model = FeedViewModel()`, each rebuild evaluates the default value, so a fresh, empty model replaces the loaded one and starts loading again. `@ObservedObject` is meant for an object passed in from outside, and Apple's documentation says not to give it a default value. `@StateObject private var model = FeedViewModel()` takes the default as an autoclosure that SwiftUI runs once for the lifetime of that view's identity, keeping the instance in storage outside the struct. Own the model with `@StateObject` in one place, then pass it to children as `@ObservedObject` or through `environmentObject(_:)`.
code
swift · 30 linesimport SwiftUI
@MainActor
final class FeedViewModel: ObservableObject {
@Published var stories: [String] = []
init() { print("FeedViewModel created") }
func load() async { stories = ["Markets rally", "Storm warning"] }
}
struct FeedView: View {
// Bug: @ObservedObject var model = FeedViewModel()
// prints "created" on every parent redraw and loses the stories.
@StateObject private var model = FeedViewModel()
var body: some View {
List(model.stories, id: \.self) { Text($0) }
.task { await model.load() }
}
}
struct NewsTab: View {
@State private var ticks = 0
var body: some View {
VStack {
Button("Refresh badge \(ticks)") { ticks += 1 }
FeedView() // rebuilt each time NewsTab's body runs
}
}
}go deeper
Remember the rule: the view that creates a model uses @StateObject; a view that is handed one uses @ObservedObject.
Explain why: view structs are rebuilt on parent redraws, a default value is re-evaluated, and @StateObject's autoclosure runs once per view identity.
Diagnose resets from symptoms: initializer logs, observed objects with default values, and identity changes above an owner that still resets its model.
Treat ownership placement as a review standard: owners sit where the data's lifetime is, and code review rejects observed objects with default values.
## The bug in one sentence A news app's feed screen declares `@ObservedObject var model = FeedViewModel()`. Every time the parent tab's `body` runs, for a badge count, a timer or a selection change, the feed empties and loads again. The cause is ownership: `@ObservedObject` **borrows** an object, it never owns one, so SwiftUI does nothing to keep the instance created by that default value. ## Why a redraw creates a new model SwiftUI views are **structs**: lightweight descriptions that SwiftUI creates again whenever a parent's `body` runs. Creating `FeedView()` runs its initializer, and the initializer evaluates every stored property's default value. With `@ObservedObject var model = FeedViewModel()`: 1. The parent's `body` runs and builds a new `FeedView` value. 2. `FeedViewModel()` runs again, producing a brand-new, empty object. 3. The observed object wrapper now points at the new instance; the old one, with its loaded stories, is released. 4. Any loading that the model starts in its initializer starts again, so the screen flickers and refetches. Apple's documentation is explicit: do not give an observed object a default or initial value, and it is unsafe to create an observed object inside a view, because SwiftUI may create or recreate a view at any time. Use the attribute only for a property that is an **input** to the view. ## What @StateObject changes `@StateObject` is the **owning** wrapper, available since iOS 14. Its initializer takes the default value as an `@autoclosure`, so writing `@StateObject private var model = FeedViewModel()` stores the expression without running it. SwiftUI runs the closure only the first time for that view and keeps the object in storage it manages outside the struct. Later struct copies find the existing object; the closure is not run again. The documentation draws the lifetime line precisely: SwiftUI creates a new instance only once during the lifetime of the container that declares the state object. It does **not** create a new instance when the view's inputs change, but it **does** when the view's identity changes, for example when a different `id(_:)` value is applied or an `if` branch swaps one view for another. Two instances of the same view, side by side, each get their own object. | | `@StateObject` | `@ObservedObject` | |---|---|---| | Role | Owner, single source of truth | Borrower, an input from outside | | Default value | Yes, evaluated once per view identity | No, the documentation says not to give one | | Survives a parent redraw | Yes | Only if the parent keeps passing the same object | | Typical declaration | `@StateObject private var model = FeedViewModel()` | `@ObservedObject var model: FeedViewModel` | ## Owning once, borrowing below The pattern is: one view owns the model with `@StateObject`, and descendants borrow it. - Pass it down explicitly to a child's `@ObservedObject` property. - Or put it into the environment with `environmentObject(_:)` and read it with `@EnvironmentObject` further down. - Get bindings to its published properties with the dollar sign, for example `$model.query` for a `TextField`. - Declare the state object `private`, so a memberwise initializer cannot overwrite the storage SwiftUI manages. ## Where to put the owner Ownership belongs at the view whose lifetime matches the data. A feed model that must survive tab switches belongs above the tabs, at the app or scene level, where `@StateObject` also works inside an `App` or `Scene`. A model tied to one detail screen belongs in that screen. If the owner is too low, every identity change of a container (a `ForEach` element getting a new identifier, a conditional branch flipping) resets the model; if it is too high, memory and loading live longer than the screen needs. ## Diagnosing it in a real app - Log in the model's initializer: a print on each parent redraw points at an observed object with a default value. - Look for `@ObservedObject` lines that end in `= SomeType()`; each one is a probable bug. - Check identity: if a `@StateObject` still resets, something above it is changing the view's identity. - On iOS 17 and later, the equivalent for an `@Observable` model is owning it in `@State`, which follows the same rule of one owner and plain references below.
- If @StateObject keeps the model, when does SwiftUI still create a new one?When the view's identity changes: a different `id(_:)` value, an `if` branch that swaps the view out, or a `ForEach` element with a new identifier. Changing the view's inputs alone keeps the same object, which is why owners belong at the level whose lifetime matches the data.
- Can a child view also declare @StateObject for a model its parent already created?It can compile if the parent passes the object into the child's initializer, but the child keeps whichever object it received first and ignores later ones. A child that receives a model should use `@ObservedObject` or read it with `@EnvironmentObject`; only the creator owns it.
- Does @StateObject avoid allocating the model on every redraw, or only avoid keeping it?It avoids allocating it. The initializer takes an `@autoclosure`, so the expression `FeedViewModel()` is stored, not run; SwiftUI runs it only the first time for that view identity. Side effects in the model's initializer therefore run once per identity, not once per redraw.
A @StateObject is a hotel room the front desk keeps for you: leave and come back as often as you like and you get the same room until you check out, which is an identity change. An @ObservedObject with a default value books a fresh, empty room every time you cross the lobby.
- Declares @ObservedObject var model = ViewModel() inside the view that needs it
- Thinks the view struct lives as long as the screen is visible
- Believes @StateObject creates one shared instance per type for the whole app
- Says @ObservedObject and @StateObject differ only in performance
- Uses @StateObject in a child for an object the parent passes in