Bird
0
0

If the parent view is recreated multiple times, what is the expected behavior regarding the observable object?

hard📝 Application Q9 of 15
iOS Swift - State Management in SwiftUI
In a SwiftUI app, a parent view creates a @StateObject instance and passes it to a child view as an @ObservedObject. If the parent view is recreated multiple times, what is the expected behavior regarding the observable object?
AThe observable object is created once and preserved, so child views see consistent data.
BA new observable object is created each time the parent view recreates, resetting the state.
CThe child view creates its own copy of the observable object, independent of the parent.
DThe observable object is destroyed immediately after the parent view is recreated.
Step-by-Step Solution
Solution:
  1. Step 1: Understand @StateObject Ownership

    @StateObject ensures the observable object is owned and preserved by the parent view.
  2. Step 2: Parent View Recreation

    Even if the parent view is recreated, SwiftUI preserves the @StateObject instance.
  3. Step 3: Child View Observation

    The child view observes the same instance via @ObservedObject, maintaining consistent state.
  4. Final Answer:

    The observable object is created once and preserved, so child views see consistent data. -> Option A
  5. Quick Check:

    @StateObject preserves instance across parent view reloads. [OK]
Quick Trick: Parent's @StateObject persists despite view reloads [OK]
Common Mistakes:
  • Assuming @StateObject recreates on every parent view reload
  • Thinking child views create new instances with @ObservedObject
  • Believing observable objects are destroyed immediately on view changes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes