如何在 Swift 中获取对应用程序委托的引用? [英] How do I get a reference to the app delegate in Swift?

查看:29
本文介绍了如何在 Swift 中获取对应用程序委托的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 中获取对应用程序委托的引用?

How do I get a reference to the app delegate in Swift?

最终,我想使用引用来访问托管对象上下文.

Ultimately, I want to use the reference to access the managed object context.

推荐答案

另一个解决方案是正确的,因为它会为您提供对应用程序委托的引用,但这将不允许您访问您添加的任何方法或变量UIApplication 的子类,就像您的托管对象上下文.要解决此问题,只需向下转换为AppDelegate"或您的 UIApplication 子类碰巧被调用的任何内容.在 Swift 3、4 &5,这样做如下:

The other solution is correct in that it will get you a reference to the application's delegate, but this will not allow you to access any methods or variables added by your subclass of UIApplication, like your managed object context. To resolve this, simply downcast to "AppDelegate" or what ever your UIApplication subclass happens to be called. In Swift 3, 4 & 5, this is done as follows:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable

这篇关于如何在 Swift 中获取对应用程序委托的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆