How do I get a reference to the app delegate in 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.


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 4.2

In Swift, easy to access in your VC's

extension UIViewController {
    var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
   }
}

Convenience Constructors

Add in AppDelegate Class at the end of code

Swift 5.5

func appDelegate() -> AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
}

To use AppDelegate reference anywhere in code?


For example: Call AppDelegate Method named setRoot

appDelegate().setRoot()


This could be used for OS X

let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = appDelegate.managedObjectContext?