1. 程式人生 > >iOS app生命週期方法執行探究

iOS app生命週期方法執行探究

使用一個新建立的沒有後臺執行的app測試:
[LogInfo] 2018-11-06 10:49:25.444
File:AppDelegate Line:30
Function:-[AppDelegate applicationWillResignActive:]
applicationWillResignActive
[LogInfo] 2018-11-06 10:49:26.030
File:AppDelegate Line:38
Function:-[AppDelegate applicationDidEnterBackground:]
applicationDidEnterBackground
[LogInfo] 2018-11-06 10:50:27.345
File:AppDelegate Line:22
Function:-[AppDelegate application:didFinishLaunchingWithOptions:]
didFinishLaunchingWithOptions
[LogInfo] 2018-11-06 10:50:27.588
File:AppDelegate Line:50
Function:-[AppDelegate applicationDidBecomeActive:]
applicationDidBecomeActive
[LogInfo] 2018-11-06 10:51:08.119
File:AppDelegate Line:30
Function:-[AppDelegate applicationWillResignActive:]
applicationWillResignActive
[LogInfo] 2018-11-06 10:51:09.153
File:AppDelegate Line:38
Function:-[AppDelegate applicationDidEnterBackground:]
applicationDidEnterBackground
[LogInfo] 2018-11-06 10:51:09.160
File:AppDelegate Line:55
Function:-[AppDelegate applicationWillTerminate:]
applicationWillTerminate

測試步驟:

  1. 切後臺,殺應用
  2. 應用前臺殺應用

可以看到步驟2呼叫了applicationWillTerminate,步驟1則不會。

但我們在一個支援後臺執行的應用中進行同樣的測試則發現,applicationWillTerminate總是會被呼叫;當切後臺的時候applicationDidEnterBackground也會正常觸發。

從這樣的結果來看,蘋果的註釋有些讓人難以理解:

  • (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.
    }

  • (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

總結:applicationWillTerminate不總是被執行,如果要保證自己的任務,需要使用beginBackgroundTaskWithExpirationHandler進行相關處理。而其具體的行為需要看你的應用是否支援後臺執行(最好用實際應用的真機測試結果來支援你的觀點,然後做好邏輯處理!)。