NSTimer计时器后台运行的解决方法

来源:互联网 发布:linux安装telnet 编辑:程序博客网 时间:2024/06/16 04:10

思路:

切换至后台计时器暂停,记录下当前时间,切换回前台计时器回复,计算中间时间差

[[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了

0 0
原创粉丝点击