1

我有一个简单的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我实例化的班级?

4

1 回答 1

1

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

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  

}


于 2020-10-17T04:47:00.107 回答