Search code examples
iosobjective-cnstimer

Multiple timers set un in the same variable


Is this code a problem?

  self.UpdateTimer = [NSTimer scheduledTimerWithTimeInterval:60. target:self selector:@selector(update:) userInfo:nil repeats:YES];

I notice that this is in a method that is called often. However there is only one place where the timer is invalidated and set to nil ... the dealloc of that class.

Does setting a new timer multiple times automatically invalidate the old timer?


Solution

  • No, setting the timer to a new object does not invalidate the previous timer. You will end up with multiple timers running if you call that line of code multiple times, but only invalidate the currently referenced timer in one place elsewhere.

    When you create the timer, you should probably check if one is already set and invalidate it before creating a new one.

    if( self.UpdateTimer )
    {
        [self.UpdateTimer invalidate];
        self.UpdateTimer = nil;
    }
    
    self.UpdateTimer = [NSTimer scheduledTimerWithTimeInterval:60. target:self selector:@selector(update:) userInfo:nil repeats:YES];
    

    OR, simply leave the original one running, if you don't need to reset the timer interval.

    if( !self.UpdateTimer )
    {
        self.UpdateTimer = [NSTimer scheduledTimerWithTimeInterval:60. target:self selector:@selector(update:) userInfo:nil repeats:YES];
    }