我有如下倒计时器:
- (void)updateCounterLabel:(NSTimer *)theTimer {
if(secondsLeft > 0 ){
secondsLeft -- ;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
else{
secondsLeft = timeInterval;
}
-(void)countdownTimer {
if([timer isValid]){
[timer invalidate];
timer = nil;
}
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounterLabel:) userInfo:nil repeats:YES];
}
----我的问题是,每次调用这个计时器时,它都会像这样递增: secondaryLeft-3 , secondaryLeft -5 ,secondLeft - 7 ......................
每次加载 View 时,我都会创建一个新计时器,但旧计时器仍然存在。在计时器的操作方法中,我会递减一个跟踪秒数的索引变量,并且每个计时器每次都会运行该方法火灾。所以,如果我有三个计时器,索引每次都会减少三。例如:
首次加载:60、59、58...
第二次加载:60、58、56...
第三次加载:60、57、54...
问题:如何重新启动或重新创建计时器而不出现上述问题?请有人帮助我。
最佳答案
timer = [NSTimer scheduledTimerWithTimeInterval:...];
call 在计时器运行时保留目标( View Controller ), 这样 View Controller 永远不会释放,即使 View Controller 被释放,计时器也会继续运行 从导航堆栈中弹出或关闭。
因此,如果再次加载 View ,您将拥有 View Controller 的两个实例,并且
因此有两个计时器,它们都会递减相同的全局变量 secondsLeft
。
这有望解释为什么该值每秒减少 2。
作为解决方案,您可以在 viewWillAppear
中创建计时器,然后使其无效
在viewWillDisappear
中。
关于iphone - NSTimer 重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17629927/