0

I have set a NSTimer and have tried invalidating it but the timer still triggers the selector. I have already tried what many threads have suggested and set and invalidated the timer on the main thread.

  • Please create a [Minimal, Complete, Verifiable Example](http://stackoverflow.com/help/mcve) before asking for help. – Jonathan Mee Jun 07 '16 at 19:50
  • In my experience, this is generally called by accidentally starting multiple timers. I'd suggest putting a log statement everywhere you start and `invalidate` timers. I bet you'll find a unbalanced pair somewhere. – Rob Jun 07 '16 at 20:12

3 Answers3

1

Solved the issue by invalidating the timer before re instantiating it.

Before:

    self.timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(self.hide), userInfo: nil, repeats: false)

After:

    self.timer?.invalidate()
        self.timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(self.hide), userInfo: nil, repeats: false)
  • Yep, that would do it. You were discarding the only reference you had to that old timer. You should go ahead and accept your own answer (as strange as that feels). – Rob Jun 07 '16 at 20:13
  • http://stackoverflow.com/help/self-answer – Rob Jun 08 '16 at 00:28
0

I was having this same problem. This was the only thing that worked for me:

Start the timer:

NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, selector:#selector(timerMethod), userInfo:nil, repeats: false)

And then in timerMethod:

func 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: false)        
     }
}

This was the only way I got it to work. Taken from here: NSTimer doesn't stop it is Mona's answer.

Community
  • 1
  • 1
Jared
  • 578
  • 7
  • 21
0

If you created it on a separate thread it won't invalidate.

Doc for invalidate() says

You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

Cjay
  • 1,093
  • 6
  • 11