NSTimer - if 语句在计时器内不起作用 - 倒计时器
我正在开发一个倒计时器,但在计数小于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我测试了你的代码,它工作得很好,计时器停在-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.看起来你的倒计时不会停止,直到它达到 -1 (而不是 0),因为你正在检查大于或等于为零,然后递减(然后显示)。
要么先递减,然后检查时间是否大于零:
或检查时间是否大于1:
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:
or check if time is greater-than 1: