Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the necessity of having a shared instance of appDelegate?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading