Search code examples
objective-ctimernstimer

NSTimer Repeats not working for me


Problem, runs once.

-(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

This is what logs, how the logic works is, firingLogic is initialised on a target lock. So the timer should run 5 times before being invalidated because of the _fireCounter counter. timer begins burst control, checks firecounter if firecounter is < 5 it fires a bullet, increases the firecounter. if the firecounter > 5 it invalidates the timer, and dispatches it to run again after 1.5 seconds.

However, the problem is that the timer is only running once. Yet, it's valid after the initial fire. Pretty confused.


Solution

  • You have to add it to the NSRunLoop. Otherwise you can use + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats