倒数计时器iphone sdk?

时间:2010-02-13 05:46:12

标签: iphone timer countdown

我的游戏中有一个倒数计时器,我正在试图弄清楚如何制作它,以便它显示两个小数位和记录,在我的表中有2个小数位。现在它作为整数倒计时并记录为整数。有什么想法吗?

-(void)updateTimerLabel{

     if(appDelegate.gameStateRunning == YES){

                            if(gameVarLevel==1){
       timeSeconds = 100;
       AllowResetTimer = NO;
       }
    timeSeconds--;
    timerLabel.text=[NSString stringWithFormat:@"Time: %d", timeSeconds];
}

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

1 个答案:

答案 0 :(得分:2)

要进行亚秒级更新,计时器的间隔需要为<但是NSTimer的精度只有50毫秒左右,因此scheduledTimerWithTimeInterval:0.01不起作用。

此外,计时器可能因各种活动而延迟,因此使用timeSeconds会导致计时不准确。通常的方法是将NSDate现在与计时器启动的日期进行比较。但是,由于此代码适用于游戏,因此当前的方法可能会减少对玩家的挫败感。如果程序或后台进程消耗大量资源。


要做的第一件事就是将countdownTimer转换为亚秒级间隔。

countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.67 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];

然后,不要把时间倒数秒,而是厘秒:

if(appDelegate.gameStateRunning == YES){
   if(gameVarLevel==1){
      timeCentiseconds = 10000;
      AllowResetTimer = NO;
   }
}
timeCentiseconds -= 67;

最后,在输出中除以100:

timerLabel.text=[NSString stringWithFormat:@"Time: %d.%02d", timeCentiseconds/100, timeCentiseconds%100];

或者,使用double

double timeSeconds;
...
if(appDelegate.gameStateRunning == YES){
   if(gameVarLevel==1){
      timeSeconds = 100;
      AllowResetTimer = NO;
   }
}
timeSeconds -= 0.67;
timerLabel.text=[NSString stringWithFormat:@"Time: %.2g", timeSeconds];