当我们在项目中需要使用计时器计时时,往往会碰到当程序进入后台时,计时器就会暂时停止,当重新进入程序时,计时器又会重新开始,然而我们需要在程序进入后台时,计时器依然能够计时,所以,就使用到了一种解决方案,利用进入后台和前台的时间差来让计时器完美计时。
首先在AppDelegate.m中,我们需要在以下两个方法添加相应通知
//当程序进入后台的时候调用
- (void)applicationWillResignActive:(UIApplication*)application {
//程序准备进入后台通知相关VC 记录当前时间
[[NSNotificationCenterdefaultCenter]postNotificationName:@"APPWillResignActive"object:nil];
}
//当程序进入前台的时候调用
- (void)applicationDidBecomeActive:(UIApplication*)application {
//程序进入前台时,记录当前时间
[[NSNotificationCenterdefaultCenter]postNotificationName:@"APPDidBecomeActive"object:nil];
}
在相对应的VC.m中注册通知,先声明一个全局的变量,NSDate * _backgroundDate;
-(void)viewWillAppear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(APPWillResignActive) name:@"APPWillResignActive" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(APPDidBecomeActive) name:@"APPDidBecomeActive" object:nil];
}
- (void)APPWillResignActive{
_backgroundDate = [NSDate date];
}
- (void)APPDidBecomeActive{
NSTimeInterval timeD = [[NSDate date] timeIntervalSinceDate:_backgroundDate];
//time 总时间
time = timeD + time;
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}