我如何在Swift中获得对AppDelegate的引用?

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


当前回答

除了这里所说的,在我的情况下,我错过了导入UIKit:

import UIKit

其他回答

这和Objective-C中的基本相同

let del = UIApplication.sharedApplication().delegate

在Swift 3.0中,你可以通过

let appDelegate = UIApplication.shared.delegate as! AppDelegate

从iOS 12.2和Swift 5.0开始,AppDelegate不能被识别。UIApplicationDelegate。因此,任何涉及AppDelegate的答案都不再正确。下面的答案是正确的,并避免了强制展开,一些开发人员认为这是一种代码气味:

import UIKit

extension UIViewController {
  var appDelegate: UIApplicationDelegate {
    guard let appDelegate = UIApplication.shared.delegate else {
      fatalError("Could not determine appDelegate.")
    }
    return appDelegate
  }
}

下面是一个UIApplicationDelegate的扩展,它避免了硬编码AppDelegate类名:

extension UIApplicationDelegate {

    static var shared: Self {    
        return UIApplication.shared.delegate! as! Self
    }
}

// use like this:
let appDelegate = MyAppDelegate.shared // will be of type MyAppDelegate

另一个解决方案是正确的,因为它会让你引用应用程序的委托,但这将不允许你访问任何方法或变量添加你的UIApplication的子类,如你的管理对象上下文。要解决这个问题,只需向下转换为“AppDelegate”或任何你的UIApplication子类碰巧被调用的东西。在Swift 3,4和5中,这样做:

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