如何运行计时器认为应用程序进入后台或终止 [英] How to run timer thought the app entered background or is terminated

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

问题描述

在我的应用程序中,我有一个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天全站免登陆