应用进入后台或终止状态时如何运行计时器 [英] How to run timer though the app entered background or is terminated

查看:70
本文介绍了应用进入后台或终止状态时如何运行计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我有一个NSTimer和一个选择器- (void)TimerCount.我还有一个整数int CountNum,每0.01秒,它会增加1(CountNum = CountNum + 1).

In my app I have a NSTimer, and a selector - (void)TimerCount. I also have a integer int CountNum, and every 0.01 second, it increases by 1 (CountNum = CountNum + 1).

Timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(TimerCount) userInfo:nil repeats:YES];

我希望计时器恢复运行,因为该应用程序已终止或进入后台.我该怎么办?

And I want the timer to resume thought the app is terminated or it entered background. How can I do this?

推荐答案

如果您的应用程序被终止,则您将无法继续处理.要在后台进行操作,需要执行诸如后台任务之类的事情,但是听起来您的用例并不保证需要执行这些任务.由于您的增量是线性且可计算的,因此您可以将开始日期分配给NSUserDefaults,然后在应用恢复时重新加载开始日期并更新计数.

If your application is terminated, you will not be able to continue processing. To operate in the background, there are such things as background tasks, but it sounds like your use case does not warrant them. Because your incrementing is linear and computable, you could assign your start date to NSUserDefaults, then load it back when your application resumes and update your count.

[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"start_time"];
NSNumber *start = [[NSUserDefaults standardUserDefaults] objectForKey:@"start_time"];
countNum = ceil([[NSDate date] timeIntervalSince1970] * 100) - ceil([start doubleValue] * 100);

这篇关于应用进入后台或终止状态时如何运行计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆