2011-07-11 142 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