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:.
    }

很明显并非只有我们关心这一点:
https://stackoverflow.com/questions/29416375/when-will-applicationwillterminate-be-called
很值得一看。

总结:applicationWillTerminate不总是被执行,如果要保证自己的任务,需要使用beginBackgroundTaskWithExpirationHandler进行相关处理。而其具体的行为需要看你的应用是否支持后台运行(最好用实际应用的真机测试结果来支持你的观点,然后做好逻辑处理!)。

你可能感兴趣的:(调试技术,ios系统能力&api)