Yuhuan Jiang
Yuhuan Jiang

Reputation: 2726

What is the relationship between the windows in UIApplication and window in AppDelegate?

In an iOS Single View App project created using Xcode, the automatically generated AppDelegate has an instance variable called window:

// In AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  // ...
  var window: UIWindow?
  // ...
}

However, the UIApplication singleton of any iOS app also has some window-related properties:

open class UIApplication : UIResponder {
  // ...
  open var keyWindow: UIWindow? { get }
  open var windows: [UIWindow] { get }
  // ...
}

My guess:

Is this correct? What is the relationship between the window of AppDelegate and the windows of UIApplication?

Upvotes: 1

Views: 328

Answers (1)

rmaddy
rmaddy

Reputation: 318804

Your guesses are correct for the typical app.

There are cases where an app may create and show additional windows. Or iOS may add additional windows to the app when using certain features. In these cases, the windows array will have more than one window (including the one referenced by the app delegate), and the keyWindow may be any one of those windows for some period of time (and not necessarily the app delegate's window).

Here is the documentation for the UIApplicationDelegate window property:

This property contains the window used to present the app’s visual content on the device’s main screen.

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.

Upvotes: 1

Related Questions