2012-10-25 97 views
0

我是一個obj-C for iOS平臺的初學者,並且正在嘗試構建一些簡單的項目來構建我的基礎。NSTimer時間增量

我有一個按鈕,它增加了標籤的NSTimer時間,但是當我使用NSLog記錄時間時,它使用時間增量實施前的值。我需要能夠記錄一個更新的時間(增量後),因爲我需要這個值,並且在我解決這個部分之後,在IBAction中實現了更多的功能。

例如在15分鐘我按下,NSLog將它讀取爲「00:15:00.0」而不是「00:35:00.0」。

- (IBAction)onSkipPressed:(id)sender { 
    startDate = [startDate dateByAddingTimeInterval:-1200]; 
    NSLog(@"%@",self.timeLabel.text); 
} 

任何人都知道這個問題的原因?我應該如何解決這個問題,如果我在15分鐘調用這個IBAction,NSLog將它讀作「00:35:00.0」。

編輯 - 開始按鈕將啓動計時器,timeLabel將獲得字符串。對不起,錯過了這樣一個重要的細節。我認爲項目中還沒有其他與此功能相關的代碼。謝謝你指出我。

- (void)updateTimer 
{ 
    NSDate *currentDate = [NSDate date]; 
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"HH:mm:ss.S"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 
    NSString *timeString=[dateFormatter stringFromDate:timerDate]; 
    timeLabel.text = timeString; 
} 

我IBAction爲火計時器

- (IBAction)onStartPressed:(id)sender { 
    startDate = [NSDate date]; 

    gameTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
               target:self 
               selector:@selector(updateTimer) 
               userInfo:nil 
               repeats:YES]; 

    //hide start button and show timeLabel 
    startButton.hidden=true; 
    timeLabel.hidden=false; 

} 
+0

你想要什麼行爲?目前尚不清楚......當您按下按鈕時,您想要顯示當前時間以及還有什麼? 你的nstimer是什麼時候創建的?何時被解僱/失效? –

+1

您的項目中是否有與此功能相關的其他代碼?這個方法中的代碼只改變了startDate的值,它並沒有將新值賦給timeLabel ... – Tobi

+0

如果用NSLog代替NSLog會發生什麼情況(@「%@」,self.startDate); ? –

回答

1

我回去做了一些修訂,參考了NSTimer的教程。而原來所有我缺少的是1號線[自updateTimer]

- (IBAction)onSkipPressed:(id)sender { 
    startDate = [startDate dateByAddingTimeInterval:-1200]; 
    [self updateTimer]; 
    NSLog(@"%@",self.timeLabel.text); 
} 

這解決了我的問題,我來記錄信息的timeLabel.text被更新。

0

嗯,你爲什麼在負1200傳遞?

// this subtracts 1200 seconds from your date, no? 
startDate = [startDate dateByAddingTimeInterval:-1200]; 

你不應該做的:

// add 30 minutes (60 seconds a minute x 30 minutes) to your time interval 
startDate = [startDate dateByAddingTimeInterval:(60 * 30)]; 
... 
NSLog(@"%@",self.timeLabel.text); 

還是我誤解的東西?

+0

說實話,我不確定(60 * 30)或-1200。因爲它實際上是由另一個人在我身上教給我的,因爲它工作,我沒有真正嘗試過。但是我現在正在我的工作站上並且讓你知道,所以我現在會去測試它。 :) –

+0

顯然使用正數會減少計時器。 –