Predict the output
Tap the child's button 3 times, then tap Refresh in the parent. What does the child show?
final class TickModel: ObservableObject {
@Published var ticks = 0
}
struct Child: View {
@ObservedObject var model = TickModel()
var body: some View {
Button("Ticks: \(model.ticks)") { model.ticks += 1 }
}
}
struct Parent: View {
@State private var refresh = 0
var body: some View {
VStack {
Button("Refresh \(refresh)") { refresh += 1 }
Child()
}
}
}Hint 1 of 2
What runs again when the parent's state changes?
Hint 2 of 2
Who owns the TickModel?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B Ticks: 0
Correct. The parent's body re-runs, Child() is re-initialized, and a new TickModel is created.
Why not the others?
- A Ticks: 3. That is what @StateObject would show. @ObservedObject doesn't own the instance.
- C Ticks: 4. Refresh doesn't touch the child's model.
- D It crashes. Nothing crashes; the state is just lost.