如何每秒更新当前时间?

时间:2016-01-11 22:15:55

标签: ios

我有一个显示时间的标签;但是,时间不会更新。时间显示,但不计算在内。显示按下按钮的时间,该时间不会改变。这是我的代码

- (IBAction)startCamera:(id)sender
{
[self.videoCamera start];

NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter setDateFormat:@"dd.MM.yyyy"];
NSString *currentDate = [dateFormatter stringFromDate:today];


for (int i = 1; i <= 10; i--) {
Label1.text = [NSString stringWithFormat:@"%@", currentTime];
Label2.text = [NSString stringWithFormat:@"%@", currentDate];    
   }

}

我尝试了for循环,但是没有更新时间。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

使用在主线程上运行的事件循环执行UI更新。你的for循环正在占用主线程,永远不会从你的启动函数返回。无论你在labelx.text中设置什么,都不会在屏幕上刷新,因为运行循环正在等待你的启动功能完成。

您应该阅读NSTimer以使用最佳做法实现此目的。

使用延迟调度还有一种方法可以做到这一点: (对不起,这是在Swift,我不知道Objective-C,但我相信你会得到这个想法)

// add this function and call it in your start function
func updateTime()
{
  // update label1 and label2 here
  // also add an exit condition to eventually stop
  let waitTime = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC )  // one second wait duration
  dispatch_after(waitTime, dispatch_get_main_queue(), {self.updateTime() }) // updateTime() calls itself every 1 second
}

答案 1 :(得分:0)

NSTimer有效,但不太准确。

当我需要准确的计时器时,我使用CADisplaylink,尤其是在处理动画时。这减少了视觉上的口吃。

使用显示器刷新准确可靠。但是,您不希望使用此方法进行繁重的计算。

- (void)startUpdateLoop {
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)];
    displayLink.frameInterval = 60;
    [displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)update {
    // set you label text here.
}
相关问题