2011-05-27 105 views
2

我正在研究一個遊戲項目。我需要知道如何顯示遊戲開始到遊戲結束的秒數?還需要以「00:01」的格式顯示。另外如果時間超過60分鐘,應該還會顯示小時「1:00:01」如何使用nstimer顯示秒數?

有什麼指導意見嗎?

謝謝...

回答

7

結合Nathan和馬克的回答後,完整的計時器方法可能是這個樣子:

- (void)timer:(NSTimer *)timer { 
    NSInteger secondsSinceStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:startDate]; 

    NSInteger seconds = secondsSinceStart % 60; 
    NSInteger minutes = (secondsSinceStart/60) % 60; 
    NSInteger hours = secondsSinceStart/(60 * 60); 
    NSString *result = nil; 
    if (hours > 0) { 
     result = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds]; 
    } 
    else { 
     result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];   
    } 
    // set result as label.text 
} 

當你開始遊戲,你設置起始日期並開始像這樣的計時器:

self.startDate = [NSDate date]; 
timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES]; 

阻止你使用這個遊戲的時候:

self.startDate = nil; 
[timer invalidate]; 
timer = nil; 
+0

'選擇器:@selector(timer :)'不需要傳遞參數?作爲 - (無效)計時器:(NSTimer *)計時器需要一個參數? – Maulik 2011-05-28 05:22:42

1

你可以安排一個重複定時器觸發每一秒,火災時它調用更新您的時間顯示的方法:在更新方法

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES]; 

然後

- (void)timerFireMethod:(NSTimer*)theTimer { 
    //remove a second from the display 
} 

您需要將計時器設置爲某個屬性,以便完成時可以使其失效。

+0

是啊...但我怎樣才能在格式顯示? – Maulik 2011-05-27 13:37:59

1

NSTimeInterval t = 10000; (int)t /(60 * 60),((int)t/60)%60,((int)t)%60);

輸出 2時46分40秒

如果你想帶小數點的秒那是有點難度,你必須使用模式

()。