获取 @EnvironmentObject 到 NSObject class

Get @EnvironmentObject to NSObject class

我有一个简单的 ObservableObject class,我在 App.swift 文件中初始化它并传递给第一个视图:

final class Counter: ObservableObject {}

@main
struct MyCoolApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self)
    private var appDelegate

    private let counter = Counter()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(counter)
        }
    }
}

效果很好,但现在我需要从我的通知代理那里得到它。基本上我有这个:

class AppDelegate: NSObject, UIApplicationDelegate {
  let notificationDelegate: NotificationDelegate
  
  func registerForPushNotifications(application: UIApplication) {
    // irrelevant code removed.
    let center = UNUserNotificationCenter.current()
    center.delegate = self?.notificationDelegate
  }
}

class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
}

在我的 NotificationDelegate class 中,如何访问我实例化的 Counter class?

这是一种可能的方式 - 使用共享实例(因为无论如何在您的场景中它只使用一个实例)

final class Counter: ObservableObject {
   static let shared = Counter()
}

struct MyCoolApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self)
    private var appDelegate

    private let counter = Counter.shared   
    
    // ...
}

...

class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {

  // use in delegate callbacks Counter.shared where needed  

}