Search code examples
iosobjective-ccocoa-touchnstimernsrunloop

NSTimer choppy when pressing buttons the second time a view loads


I'm creating a game view controller using an NSTimer to update a progress bar representing the remaining time of the current game round. This game view also displays a button performing some light core data updates. When the remaining time is up, the timer is invalidated and a new view is pushed.

The first time the game view loads in the application life cycle, it works perfectly: no slowdowns when pressing the button and updating core data. But when I'm pushing back the same game view in the application life cycle, button presses make the progress bar choppy and irresponsible.

Is the NSTimer not properly invalidated in the run loop? Should I use CADisplayLink instead, though my view isn't using a lot of resources?

Thanks in advance.

Here is my code:

Timer declaration in .h file :

@property (weak, nonatomic) NSTimer *updatetimer;

Timer creation in viewDidLoad:

self.updatetimer = [NSTimer timerWithTimeInterval:counterStep target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.updatetimer forMode:NSRunLoopCommonModes];

updateProgress function :

  - (void)updateProgress
    {
        //compute current time
        currentTime = currentTime - counterStep;

        //set timer label to int value of current time
        self.timerLabel.text = [[NSString alloc] initWithFormat:@"%d",[[NSNumber numberWithDouble:currentTime] intValue]];

        //update progress bar accordingly
        [self.progressbar setProgress: currentTime / totalTime animated:YES];

        if(currentTime <= 0) 
        {   
            //call the method that invalidates the timer + pushes to the next view
            [self overallTimeEnd];
        }
    }

Timer invalidation:

[self.updatetimer invalidate];
self.updatetimer = nil;

Solution

  • So, finally found what was causing my timer not being deallocated over the application life cycle: I wasn't using unwind segues in my storyboard to go back between views but standard push segues. Never used those before and didn't knew about them ... Thanks to all of you for helping.