gpt4 book ai didi

ios - NSTimer 发射超过它应该的

转载 作者:行者123 更新时间:2023-11-28 18:57:23 25 4
gpt4 key购买 nike

我知道这是我的问题而不是 NSTimer 的问题,但如果有人能帮助我,我将不胜感激。在我的项目中,我需要每 0.5 秒为 2 个对象调用此方法。问题是计时器在不同的时间触发。它可能会立即触发 3 或 5 次(两个对象一起触发),然后它会在 0.5 秒后重复执行相同的操作。

-(void) blinkLamp{
switch (currentState) {
case blinkingGreen:
NSLog(@"blink green lamp");
self.greenLamp = !self.greenLamp;
self.colorState[0] = [NSNumber numberWithBool:greenLamp];
self.rndValuesChanged = rand();
break;
case blinkingYellow:
NSLog(@"blink yellow lamp");
self.yellowLamp = !self.yellowLamp;
self.colorState[1] = [NSNumber numberWithBool:yellowLamp];
self.rndValuesChanged = rand();
break;
default:
break;
}
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(blinkLamp) userInfo:nil repeats:NO];
}

此方法在 SetState 方法中调用一次。

-(void) setState:(State)newState{
currentState = newState;
switch (newState) {
case green:
self.greenLamp = YES;
self.yellowLamp = NO;
self.redLamp = NO;
break;
case yellow:
self.greenLamp = NO;
self.yellowLamp = YES;
self.redLamp = NO;
break;
case red:
self.greenLamp = NO;
self.yellowLamp = NO;
self.redLamp = YES;
break;
case redYellow:
self.greenLamp = NO;
self.yellowLamp = YES;
self.redLamp = YES;
break;
case off:
self.greenLamp = NO;
self.yellowLamp = NO;
self.redLamp = NO;
break;
case blinkingGreen:
self.greenLamp = YES;
self.yellowLamp = NO;
self.redLamp = NO;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(blinkLamp) userInfo:nil repeats:NO];
break;
case blinkingYellow:{
self.greenLamp = NO;
self.yellowLamp = YES;
self.redLamp = NO;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(blinkLamp) userInfo:nil repeats:NO];
//[self blinkLamp];

break;}
default:
NSLog(@"This mode is not allowed for VehicleTL");
break;}
NSLog(@"G - %d Y - %d R - %d", self.greenLamp, self.yellowLamp, self.redLamp);
self.colorState[0] = [NSNumber numberWithBool:greenLamp];
self.colorState[1] = [NSNumber numberWithBool:yellowLamp];
self.colorState[2] = [NSNumber numberWithBool:redLamp];
self.rndValuesChanged = rand();

最佳答案

您没有跟踪现有计时器,而是创建了多个计时器,这就是您让它们多次触发的原因。

使用实例变量,并且只在当前无效时创建一个计时器:

case blinkingGreen:
self.greenLamp = YES;
self.yellowLamp = NO;
self.redLamp = NO;
[self createBlinkingTimer];
break;
case blinkingYellow:{
self.greenLamp = NO;
self.yellowLamp = YES;
self.redLamp = NO;
[self createBlinkingTimer];
//[self blinkLamp];

...

- (void)createBlinkingTimer
{
if (!self.blinkingTimer.isValid)
self.blinkingTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(blinkLamp) userInfo:nil repeats:NO];
}

关于ios - NSTimer 发射超过它应该的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30866163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com