NSTimer - if 语句在计时器内不起作用 - 倒计时器

发布于 2024-10-02 11:28:15 字数 727 浏览 0 评论 0原文

我正在开发一个倒计时器,但在计数小于 0 时无法使用 if 语句来停止计时器。任何有关解决此问题的指导将不胜感激。预先感谢您的帮助..

   -(void) startCountdown{
time = 90;
//NSLog[@"Time Left %d Seconds", time];
//This timer will call the function updateInterface every 1 second

   myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateInterface:) userInfo:nil repeats:YES];
}



-(void) updateInterface:(NSTimer*)theTimer{
if(time >= 0){
    time --;
    CountDownText.text = [NSString stringWithFormat:@"%d", time];
    NSLog(@"Time Left %d Seconds", time);
}
else{
    CountDownText.text =@"Times Up!";
    NSLog(@"Times Up!");
    // Timer gets killed and no longer calls updateInterface
    [myTimer invalidate];
}
}

I am working on a count down timer and am having trouble getting the if statement to stop the timer when the count is less that 0. Any guidance on solving this would be greatly appreciated. Thanks in advance for your help..

   -(void) startCountdown{
time = 90;
//NSLog[@"Time Left %d Seconds", time];
//This timer will call the function updateInterface every 1 second

   myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateInterface:) userInfo:nil repeats:YES];
}



-(void) updateInterface:(NSTimer*)theTimer{
if(time >= 0){
    time --;
    CountDownText.text = [NSString stringWithFormat:@"%d", time];
    NSLog(@"Time Left %d Seconds", time);
}
else{
    CountDownText.text =@"Times Up!";
    NSLog(@"Times Up!");
    // Timer gets killed and no longer calls updateInterface
    [myTimer invalidate];
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七分※倦醒 2024-10-09 11:28:15

我测试了你的代码,它工作得很好,计时器停在-1。所以我最好的猜测是 time 可能被声明为无符号值,因此它永远不会小于零。

I tested your code and it worked perfectly and the timer stopped at -1. So my best guess is that time might be declared as unsigned value, so it never becomes less than zero.

離殇 2024-10-09 11:28:15

看起来你的倒计时不会停止,直到它达到 -1 (而不是 0),因为你正在检查大于或等于为零,然后递减(然后显示)。

要么先递减,然后检查时间是否大于零:

-(void) updateInterface:(NSTimer*)theTimer{
    time --;
    if(time > 0){
        CountDownText.text = ...

或检查时间是否大于1:

-(void) updateInterface:(NSTimer*)theTimer{
    if(time > 1){
        time --;
        CountDownText.text = ...

Looks like your countdown won't stop until it gets to -1 (instead of 0) because you're checking for greater-than-or-equal to zero and then decrementing (and then displaying).

Either decrement first and then check if time is greater-than zero:

-(void) updateInterface:(NSTimer*)theTimer{
    time --;
    if(time > 0){
        CountDownText.text = ...

or check if time is greater-than 1:

-(void) updateInterface:(NSTimer*)theTimer{
    if(time > 1){
        time --;
        CountDownText.text = ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文