Search code examples
iosobjective-cnstimer

How to stop an NSTimer?


I have an NSTimer that I want to be stopped when I leave my vViewVontroller:

The timer is in a method that I call from viewWillAppear :

- (void) myMehtod
{
    //timer = [[NSTimer alloc] init];
    // appel de la methode chaque 10 secondes.
     timer  =  [NSTimer scheduledTimerWithTimeInterval:10.0f
                                     target:self selector:@selector(AnotherMethod) userInfo:nil repeats:YES];
    //self.timerUsed = timer;
}

I call the method stopTimer in viewWillDisappear

- (void) stopTimer
{
    [timer invalidate];
    timer = nil;
}

PS: I tried the answer of user1045302 in this question but it didn't work:

How to stop NSTimer


Solution

  • The source of the problem probably is that myMehtod is called twice or more times.

    Since the method does not invalidate existing timers before setting up the new one you actually have several timers ticking at the same time.

    Fix is easy: invalidate old timers before setting up a new one:

    - (void)myMehtod
    {
        [timer invalidate];
        timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
                                                 target:self
                                               selector:@selector(anotherMethod)
                                               userInfo:nil
                                                repeats:YES];
    }