当你想要对程序的不同状态进行操作时,就要对程序的生命周期进行了解,比如当你点击home键时或者程序意外退出事,需要保存现场VIew以及一些数据,应该在哪里进行操作,程序开启时启动界面,或者再次进入时直接验证登录,等等
今天就来讲一下iOS的程序生命周期,在什么时候调什么方法。
在Appdelegate中已经写好了各种监听程序状态的回调方法,所以只要了解那些方法在哪里调用就可以 了:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
NSLog(@"程序开始");
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// 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.
NSLog(@"程序暂停");
}
- (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.
NSLog(@"程序进入后台");
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// 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.
NSLog(@"程序进入前台");
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// 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.
NSLog(@"程序再次激活");
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
NSLog(@"程序意外终止");
} 比如:
程序进入后台(home键)会打印:“程序暂停”,“程序进入后台”
程序再次进入会打印:“程序进入前台”,“程序再次激活”
所以在对应的方法中加入操作即可
本文详细介绍了iOS应用程序的各种生命周期状态及其对应的回调方法。包括程序启动、暂停、进入后台、再次激活等场景,帮助开发者理解何时执行何种操作。
253

被折叠的 条评论
为什么被折叠?



