NSTimer重复不适合我

时间:2015-09-16 12:43:16

标签: objective-c timer nstimer

问题,运行一次。

-(void)firingLogicForPlayer:(Player *)player {

    if (player.playerTargetLock) {
        if (!_fireRateTimer) {
            _fireCounter = 0;

            _fireRateTimer = [NSTimer timerWithTimeInterval:1
                                                     target:self
                                                   selector:@selector(burstControl:)
                                                   userInfo:player.name
                                                    repeats:YES];

            [_fireRateTimer fire];

            BOOL timerState = [_fireRateTimer isValid];
            NSLog(@"Timer validity is: %@", timerState?@"YES":@"NO");
        }
    }

}

-(void)burstControl:(NSTimer *)theTimer {

    NSLog(@"burstControl Initiated");

    NSString *playerName = (NSString *)[theTimer userInfo];

    Player *player = (Player *)[self childNodeWithName:playerName];

    if (_fireCounter < 5) {
        [self playerBeginFiring:player];

        _fireCounter++;
    } else {
        NSLog(@"this ran to kill timer");

        [_fireRateTimer invalidate];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self firingLogicForPlayer:player];
        });
    }

}

2015-09-16 13:37:44.964 ***[20592:3367845] burstControl Initiated 2015-09-16 13:37:44.974 ***[20592:3367845] Timer validity is: YES 2015-09-16 13:37:45.147 ***[20592:3367845] hit made

这就是日志,逻辑是如何工作的,firingLogic在目标锁上初始化。因此,由于_fireCounter计数器,计时器应该在无效之前运行5次。计时器开始爆破控制,如果火灾计数器是&lt;计时器,则检查火灾计数器。 5它发射子弹,增加火焰计数器。如果消防员&gt; 5它使计时器无效,并在1.5秒后发送它再次运行。

然而,问题是计时器只运行一次。然而,它在最初的火灾后有效。很困惑。

2 个答案:

答案 0 :(得分:1)

您必须将其添加到NSRunLoop。否则,您可以使用+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

答案 1 :(得分:0)

请检查以下代码

if (!_fireRateTimer) {
    _fireCounter = 0;
    _fireRateTimer = [NSTimer timerWithTimeInterval:1
                                             target:self
                                           selector:@selector(burstControl:)
                                           userInfo:nil
                                            repeats:YES];

    [[NSRunLoop mainRunLoop] addTimer:_fireRateTimer forMode:NSDefaultRunLoopMode];

    BOOL timerState = [_fireRateTimer isValid];
    NSLog(@"Timer validity is: %@", timerState?@"YES":@"NO");
}

谢谢:)