Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swiftui 将@EnvironmentObject获取到NSObject类_Swiftui_Observableobject_Environmentobject - Fatal编程技术网

Swiftui 将@EnvironmentObject获取到NSObject类

Swiftui 将@EnvironmentObject获取到NSObject类,swiftui,observableobject,environmentobject,Swiftui,Observableobject,Environmentobject,我在App.swift文件中初始化了一个简单的observateObject类,并将其传递到第一个视图: final类计数器:observeObject{} @主要 结构MyCoolApp:App{ @UIApplicationDelegateAdaptor(AppDelegate.self) 私有变量appDelegate 私人出租计数器=计数器() var body:一些场景{ 窗口组{ ContentView() .environmentObject(计数器) } } } 这很好,但现在

我在App.swift文件中初始化了一个简单的
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  

}