2016-01-11 75 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倍。所以它確實取決於你使用的是什麼。在這裏比較合適,比低層次的方法更適合,比如我在下面建議的方法,或者是核心動畫中的更低層次的方法。 –