【问题标题】:How to access the Swift struct conforming to the App protocol from the AppDelegate [duplicate]如何从 AppDelegate 访问符合 App 协议的 Swift 结构 [重复]
【发布时间】:2021-06-04 06:05:12
【问题描述】:

很抱歉,如果这是一个已回答的问题,但“Swift”、“应用程序”和“协议”都是太笼统的术语,无法保证获得好的结果。

我有一个用于测试的套接字模拟器应用程序,它有一个以服务器为属性的 App 结构:

@main
struct RelayEmulatorApp: App {

   var socketServer : SocketServer


   @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
}

然后在我的 appDelegate 中,我覆盖了我想要优雅地关闭套接字服务器的 applicationWillTerminate。我发现由于 socketServer 的 deinit 调用了 NIO 的 syncShutdownGracefully ,这在应用程序终止时没有调用,我必须在 AppDelegate 中显式调用它(当进程没有时,操作系统显然很慢关闭套接字以终止进程这样做——我想)。

class AppDelegate: NSObject, NSApplicationDelegate {

  func applicationWillTerminate(_ notification: Notification) {

  }

}

但是我如何在 AppDelegate 中引用 App 结构的实例(我想它正在由 @main 注释实例化)以及它的属性以优雅地关闭套接字?

【问题讨论】:

  • 这是否回答了您的问题stackoverflow.com/a/63597866/12299030?
  • 嗯,它可以,但我认为我更喜欢 Tarun Tyagi 的解决方案,即根据该解决方案中建议的单例 GOD AppState 对象注入所需的位。

标签: ios swift macos swiftui


【解决方案1】:

在RelayEmulatorApp内部,socketServer被实例化后,你可以将它赋值给appDelegate变量。

@main
struct RelayEmulatorApp: App {

   var socketServer : SocketServer

   @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

   func someFunctionThatInstantiatesSocketServer() {
       /// Instantiation for sockectServer is done at this point
       appDelegate.socketServer = socketServer
   }
}

然后您将可以在AppDelegate 类中访问此实例。

class AppDelegate: NSObject, NSApplicationDelegate {

  var socketServer : SocketServer

  func applicationWillTerminate(_ notification: Notification) {
      /// socketServer.close() 
  }

}

【讨论】:

  • 啊,好建议。最好按照您的建议注入所需的东西,而不是试图依赖父母。
猜你喜欢
  • 2017-03-10
  • 1970-01-01
  • 2017-06-05
  • 2017-10-02
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多