Swiftui 将@EnvironmentObject获取到NSObject类
我在App.swift文件中初始化了一个简单的Swiftui 将@EnvironmentObject获取到NSObject类,swiftui,observableobject,environmentobject,Swiftui,Observableobject,Environmentobject,我在App.swift文件中初始化了一个简单的observateObject类,并将其传递到第一个视图: final类计数器:observeObject{} @主要 结构MyCoolApp:App{ @UIApplicationDelegateAdaptor(AppDelegate.self) 私有变量appDelegate 私人出租计数器=计数器() var body:一些场景{ 窗口组{ ContentView() .environmentObject(计数器) } } } 这很好,但现在
observateObject
类,并将其传递到第一个视图:
final类计数器:observeObject{}
@主要
结构MyCoolApp:App{
@UIApplicationDelegateAdaptor(AppDelegate.self)
私有变量appDelegate
私人出租计数器=计数器()
var body:一些场景{
窗口组{
ContentView()
.environmentObject(计数器)
}
}
}
这很好,但现在我需要从通知代理那里了解它。基本上我有:
class AppDelegate:NSObject,UIApplicationDelegate{
让notificationDelegate:notificationDelegate
func注册表形式通知(应用程序:UIApplication){
//删除不相关的代码。
let center=UNUserNotificationCenter.current()
center.delegate=self?.notificationDelegate
}
}
类NotificationDelegate:NSObject,UnuseNotificationCenterDelegate{
}
在我的
NotificationDelegate
类中,我如何访问我实例化的计数器
类?这里是一种可能的方法-使用共享实例(因为在您的场景中,它只使用一个实例)
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
}