iOS app生命周期方法执行探究

Posted openglnewbee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 app生命周期方法执行探究的主要内容,如果未能解决你的问题,请参考以下文章

iOS系列 基础篇 03 探究应用生命周期

应用程序执行的生命周期

图解ios程序生命周期

关于FragmentManager动态管理Fragment时Fragment生命周期的探究

程序猿们,iOS中是有生命周期的

Eclipse 调试器变量生命周期视图