将运行计数显示计时器添加到iOS应用程序,如时钟秒表?

Ale*_*one 14 time cocoa-touch objective-c nstimer ios

我正在使用一个处理设备运动事件的应用程序,并以5秒为增量更新界面.我想在应用程序中添加一个指示器,显示应用程序运行的总时间.看起来类似秒表的计数器,就像本机iOS时钟应用程序一样,是计算应用程序运行时间并将其显示给用户的合理方式.

我不确定的是这种秒表的技术实现.这就是我的想法:

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

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

  • 我可以使用具有短时间样式的NSDateFormatter将更新的日期转换为使用stringFromDate方法的字符串

  • 结果字符串可以分配给界面中的标签.

  • 结果是秒表针对应用的每个"滴答"进行更新.

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

ter*_*wis 24

如果你在基本横幅项目中查看Apple的iAd示例代码,他们就有一个简单的计时器:

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

以及他们拥有的方法

- (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];
}
Run Code Online (Sandbox Code Playgroud)

它只是从启动运行,非常基本.


dan*_*anh 22

几乎所有@terry lewis建议但是使用算法调整:

1)安排计时器

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

2)当计时器触发时,获取当前时间(即调整,不计入滴答,因为如果计时器中存在摆动,滴答计数将累积错误),然后更新UI.此外,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];
}
Run Code Online (Sandbox Code Playgroud)