I schedule a timer with NSTimer’s function in viewWillAppear as follows:
minutesTimer = nil;
minutesTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(updateScrollViewItems) userInfo:NULL repeats:YES];
With this function call, I expect it to call the selector updateScrollViewItems every minute, but it does not, it update items faster than expected (around some seconds).
What is the cause of this unexpected behavior?
It might not be the direct cause of the issue you’re seeing, but I can already spot one major error.
The fact that this timer is set up each time on
viewWillAppearmeans that whenever your view appears, you’re creating a new timer (and leaking the old one) which will fire 60 seconds after creation.If your view disappears and reappears multiple times, you’re going to have multiple timers all firing the same method at completely random intervals.
You need to manage the timer properly. If you want it to start when the view is first created and keep ticking/firing even when the view is not shown, then you need to create it during
init, orviewDidLoad, and then be sure to stop it when youdeallocorviewDidUnload.If you want your timer to only tick/fire when the view is the current view, then you need to ensure you’re managing stopping and starting the timer appropriately on
viewDidAppearandviewWillDisappear.Also, as Williham Totland said in his answer, NSTimer shouldn’t be relied upon for exact timing. This is also stated in the documentation:
In this case, with a time span of 60 seconds, it shouldn’t be a problem that the timer is not exact, I think the issues you’re seeing are because the timer isn’t being managed properly.