Bird
0
0

You want to create a SwiftUI view that owns a timer object which publishes the current time every second. Which approach correctly uses @StateObject to achieve this?

hard📝 Application Q8 of 15
iOS Swift - State Management in SwiftUI
You want to create a SwiftUI view that owns a timer object which publishes the current time every second. Which approach correctly uses @StateObject to achieve this?
ACreate a struct TimerModel and use @StateObject var timer = TimerModel().
BUse @ObservedObject var timer = TimerModel() in the view without initialization.
CUse @State var timer = TimerModel() in the view.
DDeclare a class TimerModel: ObservableObject with @Published time, then use @StateObject var timer = TimerModel() in the view.
Step-by-Step Solution
Solution:
  1. Step 1: Define observable object ownership and use @StateObject to own the timer

    The timer must be a class conforming to ObservableObject with @Published properties. @StateObject creates and owns the TimerModel instance, ensuring updates trigger UI refresh.
  2. Final Answer:

    Declare a class TimerModel: ObservableObject with @Published time, then use @StateObject var timer = TimerModel() in the view. -> Option D
  3. Quick Check:

    @StateObject owns observable class instances [OK]
Quick Trick: Use @StateObject with ObservableObject classes for ownership [OK]
Common Mistakes:
  • Using @ObservedObject without ownership
  • Using @State with class objects
  • Defining TimerModel as struct instead of class

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes