nstimer 倒计时未按预期工作

nstimer count down not working as expected

我正在使用 nstimer 在标签中显示倒数计时器。我能够启动计时器并在标签中显示倒计时,但计时器跳转到下一秒而不是每秒显示一次。如果倒数计时器设置为 10 秒,则倒数计时器标签中仅显示 9、7、5、3、1。

下面是我的代码。

 NSTimer *tktTimer;
 int secondsLeft;


- (void)startTimer {
   secondsLeft = 10;
        tktTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

-(void) updateCountdown {
    int hours, minutes, seconds;

    secondsLeft--;
    NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];


    if (--secondsLeft == 0) {
        [tktTimer invalidate];
        countDownlabel.text = @"Completed";
    }


}

任何帮助将不胜感激。

--secondsLeft 更新变量。要检查下一个减量是否为 0,请使用 if (secondsLeft - 1 == 0)

每次报价都会使变量递减两次。

此外,这会在 1 而不是 0 上触发 "Completed" 文本。下面是处理此问题的更好方法:

-(void) updateCountdown {
    int hours, minutes, seconds;

    secondsLeft--;
    if (secondsLeft == 0) {
        [tktTimer invalidate];
        countDownlabel.text = @"Completed";
        return;
    }        
    NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}

//用简单易懂的代码执行定时器的甜蜜而简单的方法

声明

 int seconds;
 NSTimer *timer;

//在viewDidLoad方法中

seconds=12;
     timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(GameOver) userInfo:nil repeats:YES ];

-(void)GameOver
{
     seconds-=1;
     lblUpTimer.text=[NSString stringWithFormat:@"%d",seconds];//shows counter in label

if(seconds==0)
[timer invalidate];
}

谢谢你