我正在使用一个应用程序来处理设备运动事件,并在5秒内更新接口。我想在应用程序中添加一个指示符,显示应用程序运行的总时间。看起来像秒表一样的计数器,比如原生的iOS时钟应用程序,是一种合理的方式来计算应用程序运行的时间并将其显示给用户。
我不确定的是这种秒表的技术实现。我是这么想的:
[[NSDate dateWithTimeInterval:(NSTimeInterval) sinceDate:(NSDate *)]将每个接口更新的局部变量转换为日期。stringFromDate方法将更新的日期转换为字符串。在我看来,这个实现有点重,不像秒表应用那样流畅。有没有一种更好、更交互式的方法来计算应用程序运行的时间?也许iOS已经为此目的提供了什么?
发布于 2012-08-22 15:45:25
泰瑞·刘易斯(Terry)建议的几乎是这样的,但通过算法的调整:
1)安排计时器
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];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];
}发布于 2012-08-22 15:38:16
如果您查看基本横幅项目中的苹果的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];
}它从一开始就开始运行,非常基本。
https://stackoverflow.com/questions/12076409
复制相似问题