思路:
切换至后台计时器暂停,记录下当前时间,切换回前台计时器回复,计算中间时间差
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterForeground) name:UIApplicationDidBecomeActiveNotification object:nil];
-(void)applicationEnterBackground{
_lastTime = CACurrentMediaTime();
if(self.runningTimer){
[self.timer setFireDate:[NSDate distantFuture]];
}
}
-(void)applicationEnterForeground{
double time = CACurrentMediaTime();
self.totalTime += (int)((time - _lastTime) * 100);
if(self.runningTimer){
[self.timer setFireDate:[NSDate date]];
}
}
我这里用的是毫秒所以*100了