I found some come that I'm having trouble to understand
let appDelegate = UIApplication.shared.delegate as! AppDelegate
which is used in a "Loader" class
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let root = storyboard.instantiateViewController(withIdentifier: "RootView")
root.modalPresentationStyle = .fullScreen
self.appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
self.appDelegate.window?.rootViewController = root
self.appDelegate.window?.makeKeyAndVisible()
but the "same code" can be found in the "AppDelegate" class
if let windowScene = scene as? UIWindowScene {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "RootView") // CHECK (???)
self.window = UIWindow(windowScene: windowScene)
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
}
I've realized that it can be used to access the AppDelegate methods and variables from other classes, but I'm failing to grasp the potential of this approach and the reason it is implemented
CodePudding user response:
You have a single instance of the application running, that is an instance of UIApplication
. And this application is assigned a delegate, which you implement. Since you can get the running application instance with UIApplication.shared
, you can also query its delegate and you thus have a "singleton" of your application delegate as a by-product.
People often end up packing a lot of code into their app delegates since it can be conveniently queried everywhere in your app and it usually "knows" or has direct or indirect access to most pieces of the app.