NSTimer Repeats 对我不起作用

NSTimer Repeats not working for me

问题,运行一次。

-(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 次。定时器开始连发控制,检查 firecounter 如果 firecounter < 5 它发射子弹,增加 firecounter。如果 firecounter > 5 它使计时器无效,并在 1.5 秒后再次将其发送到 运行。

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

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

请检查下面的代码

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");
}

谢谢:)