UIApplication 如何知道何时在应用程序中创建 UIWindow?

How UIApplication knows when a UIWindow is created in the app?

UIApplicationDelegateapplication:didFinishLaunchingWithOptions:中我有以下代码:

NSLog(@"%d\n", [UIApplication sharedApplication].windows.count);

self.mainWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];

NSLog(@"%d\n", [UIApplication sharedApplication].windows.count);

(mainWindow 是在 header 中声明的 @property)

第一个 NSLog 打印出 0 而第二个打印出 1.

UIApplication如何知道在应用程序中创建并初始化了一个window?

虽然我们没有 100% 确定的源代码,但 UIWindow 的初始化程序似乎是为了告诉 UIApplication 它已经创建。它只是 Apple 实现的两个 类.

的一部分

苹果 doc

When an app is launched, the system calls the UIApplicationMain function; among its other tasks, this function creates a singleton UIApplication object. Thereafter you access the object by calling the sharedApplication class method. A major role of your app’s application object is to handle the initial routing of incoming user events. It dispatches action messages forwarded to it by control objects (instances of the UIControl class) to appropriate target objects. The application object maintains a list of open windows (UIWindow objects) and through those can retrieve any of the app’s UIView objects.

如果您正在寻找特定功能(挂钩或只是好奇),UIWindow 中的大部分应用程序设置都是在 - (void)_createContextIfNecessaryForCurrentApplicationState; method and the NSISEngineDelegate 协议方法中执行的。