获取@EnvironmentObject到NSObject类

时间:2020-10-16 22:18:13

标签: swiftui observableobject environmentobject

我有一个简单的ObservableObject类,该类在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类中,如何访问我实例化的Counter类?

1 个答案:

答案 0 :(得分:0)

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

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  

}