在AppDelegate中有如下两个方法要注意:
applicationDidEnterBackground() 当应用进入后台时起作用
applicationWillTerminate() 当应用终止的时候起作用
有了这两个方法,我们就可以对程序数据进行保护。
比如当应用崩溃,内存不足被系统终止,程序在后台呆太久被终止掉时,可以通过这两个方法对操作数据进行保存,以免数据丢失。
原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_722.html
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
//当应用进入后台时其作用
func applicationDidEnterBackground(application: UIApplication) {
saveData()
}
//当应用终止的时候起作用
func applicationWillTerminate(application: UIApplication) {
saveData()
}
func saveData(){
//获取导航控制器
let navigation = self.window?.rootViewController as UINavigationController
//获取导航控制器的根视图控制器
var controller:ViewController = navigation.viewControllers.first! as ViewController
//执行ViewController的自定义数据保存方法
controller.saveData()
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
}
网友评论