22

I've got a timer which fires when the viewWillAppear method is being called and invalidates when the viewDidDisappear method is being called. But after a certain amount of switching between views the timer continues firing even after it was invalidated. What's the problem?

Here is my code:

NSTimer *timer;

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    timer = [NSTimer scheduledTimerWithTimeInterval: 0.2f
                     target: self
                     selector:@selector( timerAction )
                     userInfo:nil
                     repeats:YES];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [timer invalidate];
    timer = nil;
}

-(void) timerAction
{
    NSLog(@"timerAction");
}
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Ilya Suzdalnitski
  • 52,598
  • 51
  • 134
  • 168

12 Answers12

38

I should have been keeping a link to the timer by retaining it. :) I've asked this question 5 months ago, and it's amazing, how much more experience I acquired. :)

timer = [ [NSTimer scheduledTimerWithTimeInterval: ...] retain];
...
...
[timer invalidate];
[timer release];
Ilya Suzdalnitski
  • 52,598
  • 51
  • 134
  • 168
14

This is an absolute solution. None of the ones above worked for me, so I did this,

where you want to start the timer,

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:NO];

The method that the timer calls,

-(void)timerMethod
{
    // do what you need to do

    if (needs to be called again) {

        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:NO];        
    }
}

hope this helps,

Mona
  • 5,939
  • 3
  • 28
  • 33
  • 2
    Indeed... It looks like an Apple bug to me. The invalidate method not working because of the repeat BOOL value set to YES seams a little weird to me – Plot Mar 01 '13 at 12:18
  • 2
    This bug still exists in iOS8. This is the only way possible to solve the issue. – Anil Oct 29 '14 at 06:18
6

A method called by a timer should have the definition

- (void)methodName:(NSTimer *)aTimer;

This way the method has the instance of timer which was fired. The way you are doing it, the method will not know whether the timer was invalidated or not.

Try changing your timer initialization to

timer = [NSTimer scheduledTimerWithTimeInterval: 0.2f target: self selector:@selector(timerAction:) userInfo:nil repeats:YES]

and the method to

-(void) timerAction:(NSTimer *)aTimer{...}

Hope that helps

lostInTransit
  • 70,519
  • 61
  • 198
  • 274
2

This may not be the issue, but you need to retain the reference to timer that is returned from scheduledTimerWithInterval:. Without doing this, your pointer to the timer might be invalid by the time you go to stop it.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    timer = [[NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(timerAction) userInfo:nil repeats:YES] retain];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [timer invalidate];
    [timer release];
    timer = nil;
    [super viewDidDisappear:animated];
}

- (void)dealloc
{
    [timer invalidate];
    [timer release];
    timer = nil;
    [super dealloc];
}

Also, try setting a breakpoint in viewDidDisappear and make sure it's getting called!

rpetrich
  • 32,196
  • 6
  • 66
  • 89
Ben Gotow
  • 14,805
  • 3
  • 42
  • 47
1

This did the trick to me in Swift

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    dispatch_async(dispatch_get_main_queue(),{ [weak self] in

        self?.idleTimer?.invalidate()
        self?.idleTimer = nil

    })

}
Pau Ballada
  • 1,491
  • 14
  • 13
1
**In .h class**

@interface 
{
NSTimer * theTimer;

}


**in .m class**

//put this code where you want to calling the NSTimer function

        theTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];



- (void)updateCounter:(NSTimer *)theTimer 
{

   // write your code here for counter update 

}


// put this code to Stop timer:

    [theTimer invalidate];
    theTimer = nil;
9to5ios
  • 5,319
  • 2
  • 37
  • 65
0

You have forgotten to release the timer in viewWillDisappear:

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [timer invalidate];
    [timer release];
    timer = nil;
}

This shouldn't cause the timer to keep firing though...

rpetrich
  • 32,196
  • 6
  • 66
  • 89
  • 1
    In this case app crushes because timer is already being released. – Ilya Suzdalnitski Jun 23 '09 at 13:44
  • Ben Gotow has the right answer here. You must retain the timer after it's created, and then invalidate and release it when you want it to stop calling you back – rpetrich Jun 23 '09 at 19:54
  • You don't /have/ to retain it, since the run loop will do that, but it's a good idea if you want to be safe. – Wevah Nov 17 '09 at 06:41
0

Of invalidate the doco says

"The run loop removes and releases the timer, either just before the invalidate method returns or at some later point."

I suppose yours is getting removed at some later point.

Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159
0

- (void)viewWillAppear:(BOOL)animated gets called again.

In fact it gets called every time you switch views or after you dismiss a modal view. Basically any time your view actually reappears on screen, not just the first time.

So in this case the timer gets restarted, even though is was invalidated before.

Matjan
  • 3,591
  • 1
  • 33
  • 31
0

After creating your timer just register it to run in NSRunLoopCommonModes:

[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];

Then invalidate method will work.

Terry
  • 339
  • 4
  • 5
0

This works for me

dispatch_async(dispatch_get_main_queue(), ^{
    [timer invalidate];
});
Habib Ali
  • 272
  • 2
  • 13
0

I had the same problem.

I can't dealloc my instance if the timer is still running, so I have to stop it before calling :

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

After calling this method my timer really stop

Bruno
  • 73
  • 8