IOS程序的运行状态(生命周期)简析

By | 2015年6月23日

当一款IOS APP被安装到设备上后,它总是存在一种状态,比如没有运行APP是一种状态,点击图标打开APP时是一种状态、APP打开加载数据完成后是一种状态。

我们把IOS APP的这种执行状态分为下面几种,理解这几个状态,对IOS开发的一个整体格局认识很重要。

状态 描述

Not running

APP还没有运行 或者 APP被系统强制中断回收了

InActive

当用户点击App图标时,APP加载数据准备显示界面时,此时APP还无法接收事件响应

Active

APP已经加载好数据,并呈现界面给用户了,此时APP已经准备好接收用户的事件相应了

Background

当用户按了Home键,回到了系统界面,此时APP自动进入Background状态,但APP还处于运行状态,只是我们看不到界面了 

Suspended

当APP在Background状态下一定时间后,如果内存不够,会被系统垃圾回收处理,在被回收前,APP会进入被挂起状态(Suspended),所有app的所有操作都将被停止掉。当挂起状态一段时间后,系统便开始清理APP占用的内存,将它完全的清除,此时APP又回到了Not Running状态

下图演示了APP的执行状态:

每个状态,IOS系统都准备了相应的委托事件,我们可以在某个状态下,实现相应的功能,比如当程序进入后台(Background)时,立即保存当前的数据。

下图是每个状态对应的委托方法:

在一个Swift语言的IOS APP中,我们可以在默认生成的AppDelegate类中找到这些方法。它是APP的入口点,也包含了APP每个执行状态的委托方法。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // 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.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // 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.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // 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.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // 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.
    }

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

默认生成的这些方法,苹果都为我们写了注释,可以非常清楚的知道是干嘛的。

可以参考官方的文档:The App Life Cycle

发表评论

电子邮件地址不会被公开。 必填项已用*标注