I have a NSTimer
that fires with an interval of 3 seconds to decrease a value. When I do an action that increases that value, I want to restart the timer to cou
I've done a little testing, and it turns out that resetting the fireDate is about four times faster than invalidating and re-creating the timer. First, I create a timer which calls the method doNothing:
if (!testTimer) {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0
target:self
selector:@selector(doNothing:)
userInfo:nil
repeats:NO];
testTimer = timer;
}
Here is the test code:
- (void) testInvalidatingTimer {
for (int n = 0; n < 10000; n++) {
[testTimer invalidate];
testTimer = nil;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0
target:self
selector:@selector(doNothing:)
userInfo:nil
repeats:NO];
testTimer = timer;
}
}
- (void) testResettingTimer {
for (int n = 0; n < 10000; n++) {
if ([testTimer isValid]) {
testTimer.fireDate = [NSDate dateWithTimeIntervalSinceNow:3.0];
}
}
}
Running that on an iPad Air yields 0.198173 s for invalidatingTimer and 0.044207 s for resettingTimer. If performance is your target, I recommend to reset the fireDate. It is also quite a bit less coding effort.