在 Swift 中从 Objective C 项目访问 App delegate

Exi*_*ris 3 objective-c ios swift

我们有一个 Objective C 项目即将获得一些新功能。这些新功能将在 Swift 中实现。到目前为止,我们已经将所有这些都与 Swift 和 Objective C 一起使用,并且大多数事情都非常容易实现。

我目前未能完成的一件事是从 swift 中访问 (objc) 应用程序委托,特别是它的方法和托管对象上下文。

我试过

let appDelegate = UIApplication.sharedApplication().delegate! as UIApplicationDelegate
Run Code Online (Sandbox Code Playgroud)

没有任何成功。

如何从我的 swift 代码访问用 Objective C 编写的应用程序委托并使用它的方法以及托管对象上下文?

Amm*_*pan 5

使用您的 appdelegate 类名而不是 UIApplicationDelegate

let appDelegate = UIApplication.sharedApplication().delegate! as <<Your Appdelegate Class>>
Run Code Online (Sandbox Code Playgroud)

并在桥接头文件中导入该 appdelegate。“Bridging-Header”用于两侧桥接