10

What's the right way to do this? The NSTimer documentation says this:

Special Considerations

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.

Since GCD doesn't assure you that a serial queue will always run blocks on the same thread, what's the right way to ensure that you schedule and invalidate an NSTimer on the same thread?

EDIT:

Following the advise of the answer below, I created MSWeakTimer (https://github.com/mindsnacks/MSWeakTimer) which is a custom timer implementation using GCD that can be used from any queue.

Javier Soto
  • 4,840
  • 4
  • 26
  • 46

1 Answers1

12

You should not install an NSTimer on an anonymous worker thread managed by GCD.

Use dispatch timer sources with GCD instead of NSTimer, c.f. dispatch_source_create(3).

NSTimer relies on the current thread's runloop, which is not something that makes sense for a GCD queue. See the WWDC2012 GCD session for more details around GCD and runloop APIs.

jhilgert00
  • 5,479
  • 2
  • 38
  • 54
das
  • 3,651
  • 17
  • 19
  • That makes a lot of sense. I guess the only exception would be the main queue, am I right? – Javier Soto Feb 02 '13 at 02:52
  • correct, as long as a process doesn't call dispatch_main(3), the main runloop and the main queue are tied and guaranteed to execute on the main thread. – das Feb 03 '13 at 02:09