Yury
Yury

Reputation: 6114

Implementing window property of UIApplicationDelegate protocol

Assume I don't use storyboards. In all examples that I saw window property in application delegate initialized in willFinishLaunchingWithOptions or didFinishLaunchingWithOptions. Why not at object initialization step? I tried to do this and all seems work fine.

Upd: to be more clear. Is this code contains any hidden issues?

class MyAppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow? = UIWindow(frame: UIScreen.main.bounds)
    
    func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
        window?.rootViewController = UIViewController() //just template to make compile possible
        window?.makeKeyAndVisible()
        return true
    }
    /* ... */
}

Upvotes: 2

Views: 2111

Answers (1)

Ilya Dudarenko
Ilya Dudarenko

Reputation: 11

I have experiment and research based on this question.

At first let's look at Apple Docs on UIApplicationDelegate's window property:

Implementation of this property is required if your app’s Info.plist file contains the UIMainStoryboardFile key. Fortunately, the Xcode project templates usually include a synthesized declaration of the property automatically for the app delegate. The default value of this synthesized property is nil, which causes the app to create a generic UIWindow object and assign it to the property. If you want to provide a custom window for your app, you must implement the getter method of this property and use it to create and return your custom window.

So if your code don't use UIMainStoryboardFile option in Info.plist, you must setup window by yourself. And my experiment shows that window property is not called by UIApplication at all. Getter is called in willFinishLaunchingWithOptions method only. As far as I can see there is no hidden issues with that approach.

If you want use UIMainStoryboardFile option you can leave window creation to UIApplication. On app's startup process UIApplication checks Info.plist for UIMainStoryboardFile key, and if there is storyboard provided, it will ask AppDelegate for window:

  • If window is nil, UIApplication creates one, assigns rootViewController to it and set it in AppDelegate.
  • If window is not nil, UIApplication assigns rootViewController to it

Upvotes: 1

Related Questions