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
Here is the Swift 5 version:
let delegate = UIApplication.shared.delegate as? AppDelegate
And to access the managed object context:
if let delegate = UIApplication.shared.delegate as? AppDelegate {
let moc = delegate.managedObjectContext
// your code here
}
or, using guard:
guard let delegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let moc = delegate.managedObjectContext
// your code here
Create a method in AppDelegate Class for ex
func sharedInstance() -> AppDelegate{
return UIApplication.sharedApplication().delegate as! AppDelegate
}
and call it some where else for ex
let appDelegate : AppDelegate = AppDelegate().sharedInstance()
func sharedInstance() -> AppDelegate{
return UIApplication.shared.delegate as! AppDelegate
}
As of iOS 12.2 and Swift 5.0, AppDelegate
is not a recognized symbol. UIApplicationDelegate
is. Any answers referring to AppDelegate
are therefore no longer correct. The following answer is correct and avoids force-unwrapping, which some developers consider a code smell:
import UIKit
extension UIViewController {
var appDelegate: UIApplicationDelegate {
guard let appDelegate = UIApplication.shared.delegate else {
fatalError("Could not determine appDelegate.")
}
return appDelegate
}
}
"crucial role"
of theUIApplicationDelegate
singleton is"...to store your app’s central data objects or any content that does not have an owning view controller."
developer.apple.com/documentation/uikit/uiapplicationdelegate – liquid