我已经搜索过了,但没有任何运气。
情况如下:
我正在构建一个应用程序,上面会有一个时钟,我需要显示准确的时间;小时、分钟和秒。
我可以每隔一秒启动一次间隔,检查新的时间并进行更新——这不是问题。但是它并不准确。它总是会有几毫秒的时间,因为我正在设置秒计数的开始。
问题,有没有任何类型的回调、协议、委托等,可以在时间变化时告诉程序?
NSTimer是一条不错的选择。
安排它。。。
NSTimeInterval interval = 1.0; // the resolution of the clock
[NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(timerFired:)
userInfo:nil
repeats:YES];
当它着火的时候。。。
- (void)timerFired:(NSTimer *)timer {
NSDate *now = [NSDate date];
// update your UI knowing now
}
相对于设备的时间,这将是非常准确的。在指定当前时间后,更新显示将需要一些时间,但相对于秒分辨率而言,这只是一个微不足道的**量。
**没有光子从屏幕传播到用户视网膜所需的时间那么小,但仍然非常小。
如果我一开始没有说得很清楚,我很抱歉。我所寻找的不是一种创建计时器的方法,而是一种使计时器与设备时间完全同步的方法。
所以,这就是我想到的:
NSInteger seconds = ((NSInteger)CFAbsoluteTimeGetCurrent() % 60);
while (true) {
NSInteger currentSeconds = ((NSInteger)CFAbsoluteTimeGetCurrent() % 60);
if(seconds != currentSeconds){
NSLog(@"Seconds changed");
// fire my timer here
break;
}
NSLog(@"currentSeconds: %i",currentSeconds);
seconds = currentSeconds;
}
正如你在日志中看到的,NSLog(@"Seconds changed")正好在秒的变化时开始,我可以在这里调用计时器来启动1秒的间隔并更新我的UI等。。。通过查看日志的时间戳,可以很容易地判断出,秒是分段的。
....
2012-04-01 15:02:03.996 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.996 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.997 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.997 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.997 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.998 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.998 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.998 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.999 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.999 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:03.999 TestApp[75701:f803] currentSeconds: 3
2012-04-01 15:02:04.000 TestApp[75701:f803] Seconds changed
只是一个想法,但KVO呢?
[NSDate addObserver:self forKeyPath:@"date" options:0 context:NULL];
我现在没有访问IDE的权限,所以我无法对此进行测试。
另一方面,为什么不使用小于1(例如0.1,10次/秒)的NSTimeInterval作为更新计时器?