我正在使用 NSTimer
,在某些情况下,我想将方法 NSTimer
调用被调用之前的时间加倍。
基本上:如果我将它设置为每 0.5 秒调用一次,我想偶尔延迟它以便它在下次调用之前等待 1.0 秒(时间加倍)。
然而,我在实现这个方面遇到了很大的困难。这是我最初的尝试:
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(timerMethod:)
userInfo:nil
repeats:YES];
}
- (void)timerMethod:(NSTimer *)timer {
static int variable = 1;
switch (variable) {
case 1:
self.stopLightLabel.textColor = [UIColor redColor];
break;
case 2:
self.stopLightLabel.textColor = [UIColor orangeColor];
break;
case 3:
self.stopLightLabel.textColor = [UIColor yellowColor];
break;
case 4: // Stop for twice as long here
self.stopLightLabel.textColor = [UIColor greenColor];
NSTimeInterval timeBetweenNowAndFireDate = [timer.fireDate timeIntervalSinceNow];
// Create a new date that is twice as far in the future in order to give a long pause
timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:(timeBetweenNowAndFireDate * 2)];
break;
case 5:
self.stopLightLabel.textColor = [UIColor blueColor];
break;
case 6:
self.stopLightLabel.textColor = [UIColor purpleColor];
break;
default:
break;
}
variable++;
}
我尝试获取现在与计时器触发之间的时间量。在上面的示例中,这应该是 0.5
。然后,我将 fireDate
设置为一个新值,该值是之前的两倍。
但是,这不起作用。
如果没有这个条件,计时器会正常工作,但显然在特定情况下不会延迟(对于那种情况,它获得的时间与其他所有时间相同)。
有了条件句,它甚至显得更短!事实上,它不会变长,直到我将它乘以 400 左右而不是 2!
我在这里做错了什么?
最佳答案
您在 timerFired 方法中调用修改 fireDate 的代码。那太早了。 fireDate 是定时器 DID 在那里触发的日期。它还没有更新。
一个简单的解决方法:将其包装在调度异步中。让计时器在您尝试修改它之前返回并更新它的 fireDate:
固定代码:
- (void)timerMethod:(NSTimer *)timer {
static int variable = 1;
dispatch_async(dispatch_get_main_queue(), ^{
[self afterTimerFired:timer];
}
}
- (void)afterTimerFired:(NSTimer *)timer {
static int variable = 1;
switch (variable) {
case 4: // Stop for twice as long here
self.stopLightLabel.textColor = [UIColor greenColor];
...
NSTimeInterval timeBetweenNowAndFireDate = [timer.fireDate timeIntervalSinceNow];
NSLog(@"%f", timeBetweenNowAndFireDate);
// Create a new date that is twice as far in the future in order to give a long pause
timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:(timeBetweenNowAndFireDate * 2)];
...
或
不要分派(dispatch)异步和 make
fireDate = [NSDate dateWithTimeIntervalSinceNow:fire.timeInterval*2]
如果可能的话可能会更干净
关于ios - 将 NSTimer 的 fireDate 之前的时间加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275958/