微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取@EnvironmentObject到NSObject类

如何解决获取@EnvironmentObject到NSObject类

我有一个简单的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类?

解决方法

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

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  

}


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。