【问题标题】:Get @EnvironmentObject to NSObject class获取@EnvironmentObject 到 NSObject 类
【发布时间】:2020-10-16 22:18:13
【问题描述】:

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

【问题讨论】:

    标签: swiftui observableobject environmentobject


    【解决方案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  
    
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多