WatchKit中UIApplication.sharedApplication()。委托的等价物是什么?

时间:2016-03-28 20:36:49

标签: objective-c swift watchkit uiapplicationdelegate wkextension

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

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

目标C:
AppDelegate *delegate = [[UIApplication sharedApplication] delegate];

在WatchKit2应用程序扩展中有一个类似的App Delegate,我想在视图控制器中获取对它的引用,以访问应用程序中的共享资源,例如我拥有的Core Data Stack的ManagedObjectModel和PersistentStoreCoordinator在App Delegate中初始化。

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

  

使用未解析的标识符'UIApplication'

如何在WatchKit2 App Extension中访问应用代理?

2 个答案:

答案 0 :(得分:3)

WatchOS 2中的WKExtension类自动为每个扩展提供单个扩展对象,以管理在所有应用程序的界面控制器之间共享的行为。 Apple Documentation注意到您“使用扩展程序对象执行应用程序级任务,例如打开网址并获取应用程序的根界面控制器。”

就像在iOS中一样,在WatchKit App Extension中,您提供自己的委托对象,即您要引用的对象。这会自动分配给WKExtension对象的delegate属性,并且可以使用与在iOS中访问UIApplication委托的方法类似的方法进行访问:

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

目标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!强制转换为非可选项是安全的,鉴于开发人员知道他们已在其App扩展中设置了WKExtensionDelegate。

答案 1 :(得分:0)

extension ExtensionDelegate {
    static var shared: ExtensionDelegate {
        guard let delegate = WKExtension.shared().delegate as? ExtensionDelegate else {
            fatalError("ExtensionDelegate")
        }
        return delegate
    }
}