【问题标题】:What is the equivalent of UIApplication.sharedApplication().delegate in WatchKit?WatchKit 中 UIApplication.sharedApplication().delegate 的等价物是什么?
【发布时间】:2016-03-28 20:36:49
【问题描述】:

在 iOS 应用程序中,您可以通过以下方式获取对共享应用程序委托的引用:

斯威夫特:
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate

Objective-C:
AppDelegate *delegate = [[UIApplication sharedApplication] delegate];

在 WatchKit2 App Extension 中有一个类似的 App Delegate,我想在视图控制器中获取对它的引用以访问应用程序中的共享资源,例如核心数据堆栈的 ManagedObjectModel 和 PersistentStoreCoordinator,我有在 App Delegate 中初始化。

但是UIApplication.sharedApplication().delegate as! AppDelegate报错,

使用未解析的标识符“UIApplication”

如何在 WatchKit2 应用扩展中访问应用委托?

【问题讨论】:

    标签: objective-c swift watchkit uiapplicationdelegate wkextension


    【解决方案1】:

    WatchOS 2 中的 WKExtension 类会自动为每个扩展提供一个扩展对象,以管理在您应用的所有界面控制器之间共享的行为。 Apple Documentation 指出您“使用扩展对象执行应用级任务,例如打开 URL 和获取应用的根界面控制器。”

    就像在 iOS 中一样,在您的 WatchKit 应用程序扩展中,您提供自己的委托对象,即您尝试引用的委托对象。这会自动分配给 WKExtension 对象的委托属性,并且可以使用与在 iOS 中访问 UIApplication 委托类似的方法来访问:

    斯威夫特:
    let delegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate

    Objective-C:
    WKExtensionDelegate *delegate = [[WKExtension sharedExtension] delegate];

    Apple documentation of the WKExtension Class 提供有关功能的更多信息。


    更深入:
    WatchKit App Extensions 并非在所有情况下都必须提供 WKExtensionDelegate。正如WKExtensionDelegate documentation from Apple 所指出的,“您提供委托对象并使用它来管理扩展中的生命周期事件。如果您的扩展支持可操作的通知或切换行为,则需要提供委托对象。”

    您将知道您的 WatchKit App Extension 是否有委托对象,如果有,那么在您的 App Extension 生命周期中,您将不会尝试访问不存在的 App Delegate。因此,虽然WKExtension.sharedExtension().delegate 是可选的(WatchKit App Extensions 可能存在于未设置委托的情况下),但在上面的示例中使用as! 强制将返回值强制转换为非可选是安全的,因为开发人员知道他们在他们的应用扩展中设置了一个 WKExtensionDelegate。

    【讨论】:

      【解决方案2】:
      extension ExtensionDelegate {
          static var shared: ExtensionDelegate {
              guard let delegate = WKExtension.shared().delegate as? ExtensionDelegate else {
                  fatalError("ExtensionDelegate")
              }
              return delegate
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-08
        • 2014-06-12
        • 1970-01-01
        • 2022-11-28
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多