2016-01-11 73 views
0

我有一个显示时间的标签;但是,时间不会更新。时间显示,但不计数。显示该按钮的时间并且时间不变。这里是我的代码如何每秒更新当前时间?

- (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循环但不更新时间。有什么建议么?

+0

For循环在基于事件的系统中是讨厌的。我会寻找一些你可以听的活动。 –

+1

调查'NSTimer'。 – rmaddy

+0

@KeithJohnHutchison你是什么意思? – Drizzle

回答

2

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

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

也有办法做到这一点使用延迟调度: (抱歉,这是斯威夫特,我不知道客观-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 
} 
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. 
} 
+0

我很惊讶NSTimer会如此不准确,以至于无法达到一秒的精度。你是否测量过这个?用户是否真的会注意到时钟秒数是否迟到了半秒? –

+0

NSTimer文档中的第三段。最终它取决于你使用的是什么。 StopWatch /节拍器我会避免NSTimer。 100ms肯定是显而易见的。对于投票给我的人,请解释原因。 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/index.html –

+0

所以即使根据规格。它足够快速达到目的。在动画场景中100ms可能会很明显,但这不适用于此。 NSTimer可以比所需的速度快10倍。所以它确实取决于你使用的是什么。在这里比较合适,比低层次的方法更适合,比如我在下面建议的方法,或者是核心动画中的更低层次的方法。 –