本文翻译自:How do I get a reference to the app delegate in Swift?
How do I get a reference to the app delegate in Swift? 如何在Swift中获得对应用程序委托的引用?
Ultimately, I want to use the reference to access the managed object context. 最终,我想使用引用来访问托管对象上下文。
#1楼
参考:https://stackoom.com/question/1ctVM/如何在Swift中获得对应用程序委托的引用
#2楼
与Objective-C几乎相同
let del = UIApplication.sharedApplication().delegate
#3楼
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. 另一个解决方案是正确的,因为它将为您提供对应用程序委托的引用,但这将不允许您访问UIApplication的子类添加的任何方法或变量,例如托管对象上下文。 To resolve this, simply downcast to "AppDelegate" or what ever your UIApplication subclass happens to be called. 要解决此问题,只需向下转换为“ AppDelegate”或您的UIApplication子类碰巧被调用的任何东西。 Like so: 像这样:
Swift 3.x (Introduced with Xcode 8) Swift 3.x(与Xcode 8一起引入)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable
Swift 1.2 - 2.x (Introduced with Xcode 6.3) Swift 1.2-2.x(Xcode 6.3引入)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable
Swift < 1.2 斯威夫特<1.2
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let aVariable = appDelegate.someVariable
#4楼
This could be used for OS X 这可以用于OS X
let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = appDelegate.managedObjectContext?
#5楼
In the Xcode 6.2, this also works 在Xcode 6.2中,这也有效
let appDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
let aVariable = appDelegate.someVariable
#6楼
Convenience Constructors 便利构造
Add in AppDelegate Class at the end of code 在代码末尾添加AppDelegate类
Swift 5 迅捷5
func appDelegate() -> AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
To use AppDelegate reference in your class? 要在您的课程中使用AppDelegate参考?
Call AppDelegate Method 调用AppDelegate方法
appDelegate().setRoot() appDelegate()。setRoot()