让你又爱又恨的iOS开发

点击app的icon之后发生了什么

2018-06-14  本文已影响19人  Sunday_gao

app的启动分为pre-main()main()两个阶段,本篇文章主要介绍main()函数发生了什么。

app_launch_fg.png

main()函数阶段

每个C语言程序都是从main()函数开始的,Objective-C的程序也不例外。创建完新的iOS工程之后,系统会默认为我们创建一个main.m文件。main.m的代码一般如下:

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

main()函数中只调用了一个函数UIApplicationMain(),接下来介绍一下UIApplicationMain()函数。

UIApplicationMain()函数

/**
 创建application及其代理,创建事件循环

 @param argc argv中参数的数量
 @param argv 参数的列表
 @param principalClassName UIApplication类名或其子类名,nil默认为UIApplication
 @param delegateClassName application delegate的类名,如果从nib文件加载代理,则设为nil(不太理解)
 @return Never Return
 */
int UIApplicationMain(int argc, char * _Nonnull *argv, NSString *principalClassName, NSString *delegateClassName);

看一下UIApplicationMain()的官方文档:

This function instantiates the application object from the principal class and instantiates the delegate (if any) from the given class and sets the delegate for the application. It also sets up the main event loop, including the application’s run loop, and begins processing events. If the application’s Info.plist file specifies a main nib file to be loaded, by including the NSMainNibFile key and a valid nib file name for the value, this function loads that nib file.
Despite the declared return type, this function never returns.

由此可知,UIApplicationMain()主要做了以下事情:

UIApplicationDelegate

UIApplicationMain()函数在完成上述的主要事情之后,会进行第一次初始化,此时会回调UIApplicationDelegateapplication:willFinishLaunchingWithOptions:方法,这是开发者能够编写自定义代码的第一个地方。
接下来会恢复UI状态,然后是最终的初始化,此时会回调UIApplicationDelegateapplication:didFinishLaunchingWithOptions:方法,在这个方法中设置keyWindow,并且创建根控制器。
以下为新建的空工程UIApplicationDelegate方法的执行顺序:

2018-06-14 02:40:17.954918+0800 AppProgrammingDemo[54037:27963804] -[AppDelegate application:willFinishLaunchingWithOptions:]
2018-06-14 02:40:17.955391+0800 AppProgrammingDemo[54037:27963804] -[AppDelegate application:didFinishLaunchingWithOptions:]
2018-06-14 02:40:17.968420+0800 AppProgrammingDemo[54037:27963804] -[AppDelegate applicationDidBecomeActive:]
2018-06-14 02:42:55.144510+0800 AppProgrammingDemo[54037:27963804] -[AppDelegate applicationWillResignActive:]
2018-06-14 02:42:55.726878+0800 AppProgrammingDemo[54037:27963804] -[AppDelegate applicationDidEnterBackground:]
2018-06-14 02:43:34.248368+0800 AppProgrammingDemo[54037:27963804] -[AppDelegate applicationWillEnterForeground:]
2018-06-14 02:43:34.533594+0800 AppProgrammingDemo[54037:27963804] -[AppDelegate applicationDidBecomeActive:]
上一篇 下一篇

猜你喜欢

热点阅读