我在这个上搜索没有任何运气。
情况如下:
我正在构建一个应用程序,它将有一个时钟,我需要显示准确的时间;小时,分钟和秒。
我可以每秒启动一个间隔并检查新时间并进行更新 - 不是问题。但是......这不准确。它总是会有几毫秒的关闭,因为我正在设置秒计数的开始。
问题,是否有任何类型的回调,协议,委托等,会在时间变化时告诉程序?
答案 0 :(得分:2)
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
}
这相对于设备的时间非常准确。分配当前时间后更新显示需要一些时间,但相对于秒分辨率需要一些微不足道的**。
**不像光子从屏幕传播到用户视网膜所需的时间那么小,但仍然很小。
答案 1 :(得分:0)
如果我一开始没说清楚,我道歉。我所寻找的不是创建计时器的方法,而是一种使计时器与设备的时间完全同步的方法。
所以,这就是我想出的:
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
答案 2 :(得分:-1)
只是一个想法,但KVO呢?
[NSDate addObserver:self forKeyPath:@"date" options:0 context:NULL];
我现在无法访问IDE,因此无法对此进行测试。
另一方面,为什么你不能只为你的更新计时器使用小于1的NSTimeInterval(例如0.1,10次/秒)?