将一个正在运行的countup显示计时器添加到一个iOS应用程序,如时钟秒表?

我正在使用一个以5秒为单位处理设备动作事件和更新界面的应用程序。 我想添加一个指标,将显示应用程序已经运行的总时间的应用程序。 似乎像秒表一样的计数器,就像本机的iOS时钟应用程序是一个合理的方式来计算应用程序已经运行的时间,并显示给用户。

我不确定的是这种秒表的技术实现。 这是我在想什么:

  • 如果我知道界面更新之间有多长时间,我可以在事件之间加上秒,并将秒数保持为局部variables。 或者,间隔0.5秒的定时器可以提供计数。

  • 如果我知道应用程序的开始date,我可以使用[[NSDate dateWithTimeInterval:(NSTimeInterval) sinceDate:(NSDate *)]将本地variables转换为每个接口更新的date

  • 我可以使用具有短时间样式的NSDateFormatter将更新date转换为使用stringFromDate方法的string

  • 结果string可以分配给界面中的标签。

  • 结果是秒表针对应用程序的每个“打勾”进行更新。

在我看来,这个实现有点太重,不像秒表应用那样stream畅。 有一个更好,更互动的方式来计算应用程序已经运行的时间? 也许iOS已经为此提供了一些东西?

刘易斯build议的几乎是什么,但algorithm调整:

1)安排一个计时器

 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES]; 

2)当定时器触发时,获取当前时间(这是调整,不计数滴答,因为如果定时器摆动,滴答计数将累积错误),然后更新用户界面。 此外,NSDateFormatter是一个更简单,更通用的方式来格式化显示的时间。

 - (void)timerTick:(NSTimer *)timer { NSDate *now = [NSDate date]; static NSDateFormatter *dateFormatter; if (!dateFormatter) { dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"h:mm:ss a"; // very simple format "8:47:22 AM" } self.myTimerLabel.text = [dateFormatter stringFromDate:now]; } 

如果您在基本横幅项目中查看来自Apple的iAd示例代码 ,则它们具有一个简单的计时器:

 NSTimer *_timer; _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES]; 

和他们的方法

 - (void)timerTick:(NSTimer *)timer { // Timers are not guaranteed to tick at the nominal rate specified, so this isn't technically accurate. // However, this is just an example to demonstrate how to stop some ongoing activity, so we can live with that inaccuracy. _ticks += 0.1; double seconds = fmod(_ticks, 60.0); double minutes = fmod(trunc(_ticks / 60.0), 60.0); double hours = trunc(_ticks / 3600.0); self.timerLabel.text = [NSString stringWithFormat:@"%02.0f:%02.0f:%04.1f", hours, minutes, seconds]; } 

它只是从开始运行,非常基本。