Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 870
AperioOculus Avatar asked Jun 04 '14 19:06

AperioOculus


People also ask

What is UIApplication delegate?

The app delegate is effectively the root object of your app, and it works in conjunction with UIApplication to manage some interactions with the system. Like the UIApplication object, UIKit creates your app delegate object early in your app's launch cycle so it's always present.

What is the difference between AppDelegate and SceneDelegate?

AppDelegate is responsible for handling application-level events, like app launch and the SceneDelegate is responsible for scene lifecycle events like scene creation, destruction and state restoration of a UISceneSession.


1 Answers

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 
like image 184
Mick MacCallum Avatar answered Sep 27 '22 18:09

Mick MacCallum