Objective c 防止倒计时变成负数
我已经创建了一个倒计时计时器,它工作得很好。。但当它达到零时,它会继续倒计时。。它显示了-1,-2,-3等等。我如何防止它这样做 这是我在实现文件中的代码Objective c 防止倒计时变成负数,objective-c,ios,cocoa,nstimer,foundation,Objective C,Ios,Cocoa,Nstimer,Foundation,我已经创建了一个倒计时计时器,它工作得很好。。但当它达到零时,它会继续倒计时。。它显示了-1,-2,-3等等。我如何防止它这样做 这是我在实现文件中的代码 @implementation ViewController -(IBAction)start { myTicker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil rep
@implementation ViewController
-(IBAction)start {
myTicker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
-(IBAction)stop {
[myTicker invalidate];
}
-(IBAction)reset {
time.text = @"0";
}
-(void)showActivity {
int currentTime = [time.text intValue];
int newTime = currentTime -1;
time.text = [NSString stringWithFormat:@"%d", newTime];
}
我猜我在什么地方丢失了一些代码?快速修复方法是更改:
int newTime = currentTime - 1;
进入:
这将阻止倒数计时器降到零以下。如果你只需要这些,那就足够了
当计时器为零时,它不会关闭计时器或执行操作。为此,您需要在上面的那一行之后添加类似于以下块的内容:
if ((currentTime > 0) && (newTime ==0)) {
// optionally turn off timer
fireZeroEvent ();
}
并提供fireZeroEvent()
函数来执行任何需要执行的操作
我建议您可以选择关闭计时器,因为您可能想让它继续运行,这样您就可以通过设置time.text
重新启动倒计时,而无需重新创建计时器
因此,仅在从1到0的转换过程中调用
fireZeroEvent()
,而不是每次计时器达到零后触发时都调用它。@user1253207:抱歉,我输入错误-第一个:
应该是?
-请再试一次。@user1253207:我会补充一点,除非你有特定的理由让计时器继续运行,否则你真的应该停止它。paxdiablo的代码并没有阻止它;您需要自己添加代码。
if ((currentTime > 0) && (newTime ==0)) {
// optionally turn off timer
fireZeroEvent ();
}