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

本文翻译自: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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值