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

问题描述

在我的应用程序中,我有一个 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);

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

09-12 17:43