iosobjective-ctimernstimerrunloop

How can I find out which run loop a certain NSTimer is on if it was created with scheduledTimerWithTimeInterval?


If I made an NSTimer with scheduledTimerWithTimeInterval, then according to the documentation, it should be added to the current run loop. I'd like to know how to check which run loop an NSTimer is on.

Also, if a timer is invalidated and a new one is created, how can I add the new timer to the same run loop that the first timer was on?

Thanks in advance.


Solution

  • I'd like to know how to check which run loop an NSTimer is on.

    When you schedule the original timer, you can save a reference to [NSRunLoop currentRunLoop] so you know to which runloop it was added. You can also use currentRunLoop when inside the timer's event handler, too.

    But there is no simple NSTimer method/property that you use to inquire as to which run loop an arbitrary NSTimer has been scheduled. Nor does the NSRunLoop object expose any method to allow the app developer to inquire as to which timers have been scheduled on that particular run loop.

    Also, if a timer is invalidated and a new one is created, how can I add the new timer to the same run loop that the first timer was on?

    In general, if you want to schedule an NSTimer on an NSRunLoop other than the current one, rather than calling scheduledTimerWithTimeInterval, you would instantiate the timer with timerWithTimeInterval and then manually add this timer to a particular NSRunLoop using the run loop's addTimer:mode: method.


    All of this begs the question as to why you're scheduling timers on any run loop other than the main one. If you want to use NSTimer from a background thread, you have to create your own run loop on that background thread (which is a little inefficient and not something you'd generally do unless you had a very compelling reason).

    Generally when using NSTimer, you would simply schedule it on the main run loop (e.g., schedule it from the main thread) and that eliminates the need for all of this convoluted logic of creating run loops, keeping track of which timer is scheduled on which run loop, as well as the logic associated with manually scheduling the new timer on the same run loop. The main run loop is generally quite adequate in gracefully handling multiple timers.

    If you really need timers that run on a thread other than the main thread, you might want to consider using GCD dispatch timers, which can be scheduled on any dispatch queue, without needing any extra run loops. (If you want to schedule more timers to the same queue as some previous timer, though, you would have to keep track of which queue the dispatch timer was added.)