2011-07-11 141 views
1

好吧,我的第一個應用程序永遠是一個計時器。正如慣例似乎是在我打了個問候世界之後。我使用NSTimer類作爲我的計時器,並且每秒都會觸發它,然後更改UILabel中的文本。現在這一切都很好,除了我第一次運行。每當我在模擬器中運行應用程序並啓動計時器時,它們在我的最後一秒都是一個奇怪的延遲,它會凍結約2秒鐘,然後繼續,如果沒有錯誤。然後它適用於每個運行的集合。NSTimer導致一些奇怪的延遲

這裏就是我成立了的NSTimer代碼:在計時器觸發方法

theTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(onTimer) userInfo:nil repeats:YES]; 

然後我打電話updateLabel

countDownLabel.text = [NSString stringWithFormat:@"%02d:%02d", startMin,startSec]; 
//Check if sets are complete 
if(setCount <= numOfSets) 
{ 
    setLabel.text = [NSString stringWithFormat:@"Set %02d of %02d", setCount, numOfSets]; 
    //check if timer is complete 
    if(startMin <= 0 && startSec <= 0) 
    { 
     countDownLabel.textColor = [UIColor greenColor]; 
     //run interval timer when timer is complete 
     if(intervalBetweenSets <= intervalBetweenSetsSetting) 
     { 
      setLabel.text = [NSString stringWithFormat:@"Starting set"]; 
      intervalBetweenSets++; 
      intervalCounterSec--; 
      countDownLabel.text = [NSString stringWithFormat:@"00:%02d", intervalCounterSec]; 
     } 
     else 
     { 
      //RESET values on timer label 
      TimerSettings *myTimer = [TimerSettings sharedManager ]; 
      startMin = myTimer.min; 
      startSec = myTimer.sec; 
      intervalBetweenSets = 0; 
      intervalCounterSec = intervalBetweenSetsSetting+1; 
      countDownLabel.textColor = [UIColor redColor]; 
      countDownLabel.text = [NSString stringWithFormat:@"%02d:%02d", startMin,startSec]; 
      setLabel.text = [NSString stringWithFormat:@"Set %02d of %02d", setCount, numOfSets]; 
     } 
    } 
    else 
    { 
     //Actual timer for display 
     if(startSec == 0) 
     { 
      startMin = startMin - 1; 
     } 
     startSec = startSec - 1; 
     if(startSec == -1) 
     { 
      startSec = 59; 
     } 
     if(startMin <= 0 && startSec < 1) 
     { 
      //increment number of completed sets 
      setCount++; 
      //play sound when timer completes 
      if (audioPlayer == nil) 
       ; 
      else 
      { 
       [audioPlayer play]; 
      } 
     } 

     countDownLabel.text = [NSString stringWithFormat:@"%02d:%02d", startMin,startSec]; 
    } 
} 

的事情是,我不知道這是否是一些問題與計時器或如果它與我的邏輯有關,如果有什麼不清楚我在做什麼,請提問,我會澄清。

感謝

+0

你是什麼意思的「凍結」?倒計時顯示停止改變?整個用戶界面不會響應觸摸? –

+0

當我說凍結其停止更新的唯一標籤時,應用程序的其餘部分保持響應。我已經通過了它,並且邏輯顯示爲聲音,並且我可以將計時器設置爲任何值,它將在00:01時始終凍結兩秒鐘,然後繼續正常運行 – Armand

回答

1

你不應該使用的NSTimer保持時間,如果那是你正在嘗試做的,NSTimers在概念放入事件提示等只能當你的程序從等待輸入火災事件提示。喲可以使用NSTimers來告訴你領域更新自己的顯示,但要獲得時間量,你應該使用NSDate方法或相等的C函數。

+0

因此,基本上你告訴我的是運行一段時間真)類循環檢查日期,然後相應地更新我的標籤文本?真的嗎? – Armand

+2

不,這會超過kill,仍然使用NSTimer,但通過記錄開始時間[start = [NSDate date]]來記錄時間,然後通過使用'[start timeIntervalSinceNow]'獲得多少時間'然後你應該改變文本字段的值併發送一個'[textView setNeedsDisplay'。 –

+0

非常感謝@Nathan – Armand