Bird
0
0

What happens if you replace @StateObject with @ObservedObject in the code below?

medium📝 Predict Output Q5 of 15
iOS Swift - State Management in SwiftUI
What happens if you replace @StateObject with @ObservedObject in the code below?
struct ContentView: View {
  @StateObject var model = MyModel()
  var body: some View { Text(model.text) }
}
AThe model will be shared correctly and state preserved.
BThe model will be recreated every time the view reloads, losing state.
CThe code will not compile due to missing initialization.
DThe UI will not update on model changes.
Step-by-Step Solution
Solution:
  1. Step 1: Understand difference between @StateObject and @ObservedObject and analyze replacement effect

    @StateObject owns and preserves the object. @ObservedObject expects the object to be created elsewhere. Using @ObservedObject here causes the model to be recreated on each view reload, losing state.
  2. Final Answer:

    The model will be recreated every time the view reloads, losing state. -> Option B
  3. Quick Check:

    @ObservedObject without external ownership recreates object [OK]
Quick Trick: Use @StateObject to own; @ObservedObject to observe owned objects [OK]
Common Mistakes:
  • Assuming @ObservedObject preserves state automatically
  • Confusing ownership and observation roles
  • Expecting compilation error instead of runtime behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes