swiftmacosswiftuiobservableobject

Can you use a @StateObject under SwiftUI App protocol?


I have created an ObservableObject like so:

class Status: ObservableObject {
  @Published var status: StatusType = .stopped
}

Which uses a custom enum StatusType that has 4 states.

I am using this ObservableObject in a View to get and set StatusType's.

struct MyView: View {
  @StateObject private var myStatus = Status()
  
  var body: some View {
    Button(action: {
      switch myStatus.status {
      case .stopped:
        start()
        myStatus.status = .started
      // more cases...

      }
   }){
      switch myStatus.status {
      case .stopped:
        Text("Stopped")
      // more cases...
   }
}

This works pretty well.

But when I try to use a @StateObject under the App protocol, it doesn't work. Xcode doesn't complain either.

I want to use the @StateObject to change my menuIcon.

struct MyApp: App {
  @StateObject private var myStatus = Status()

  private var menuIcon: String {
    return myStatus.status == .started ? "started" : "stopped"
  }
  
  var body: some Scene {
    MenuBarExtra {
    // views
    } label: {
      // use menuIcon here
      }
  }

}

What am I missing? Would appreciate some pointers!


Solution

  • you have to observe the status object, You can make your Status a singleton. This ensures that there is only one instance of it throughout the app

    class Status: ObservableObject {
        static let shared = Status()
    
        @Published var status: StatusType = .stopped
    }
    
    @main
    struct MyApp: App {
        @ObservedObject private var myStatus = Status.shared
        
        //... rest of your code
    }