程序入口爲main函數,如下以原始未改動的main函數爲例app
int main(int argc, char * argv[]) { @autoreleasepool { NSLog(@"%s",__func__); return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
main函數中會調用 UIApplicationMain(int argc, char *argv[], NSString * __nullable principalClassName, NSString * __nullable delegateClassName);第3、四個參數表明主要類和代理類,若主要類爲nil,則默認爲UIApplication,若是代理類爲nil,則從Main nib文件中加載代理對象。UIApplication對象會監控應用程序的生命週期,並由代理對象處理監聽到的事件。函數
應用會開啓主運行循環,進行事件的處理(首先會啓動完畢後調用代理對象的如下方法)ui
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions
在這個方法中會實例化一個UIWindow對象設置其屬性,如frame,設爲代理對象的主窗口,還有就是設置UIWindow的根視圖控制器,顯示主窗口,程序會根據根視圖控制器的具體狀況加載對應的View到主窗口上。this
3.UIApplication代理對象中,和生命週期有關的部分方法以下
spa
a.當應用程序進入非活動狀態時調用,在此期間不接收消息或事件,好比來電
代理
- (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. }
b.當程序被推送到後臺時調用,若要設置後臺繼續運行,可在此方法中設置
rest
- (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. }
c.當程序將從後臺轉爲前臺運行時調用。
code
- (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. }
d.當程序進入活動狀態時執行,可接收消息或事件
orm
- (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. }
e.當程序退出時調用,一般是保存數據,和清理工做
對象
- (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. }