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