8

I didn't explicitly add timers to a runloop and it works just fine. The other day when I read some article about NSRunLoop and it said it's better to add a NSTimer instance into a runloop instance to execute. I just wonder will it do any harm if I don't do so?

Xin Yuan
  • 255
  • 1
  • 8

2 Answers2

12

NSTimer instances always need to be scheduled on a run loop to operate properly. If you're doing it from the main thread, you can just use scheduleTimerWithTimeInterval and it will automatically added to the main run loop for you and no manual call to NSRunLoop method addTimer is needed. But you can create timer and add it yourself, if you want. The scheduleTimerWithTimeInterval is a convenience method that just does that for you.


If you are creating a timer from a background thread that doesn't have its own run loop (and by default, when you use background dispatch queues or operation queues, the thread on which that is running will not have its own run loop), you then have to manually add the timer to a run loop. Typically, people will just add the timer to the main run loop.

Alternatively, if you really want a timer to run on a background thread, rather than creating a run loop for that thread and adding the timer to that new run loop, you can use GCD dispatch timers, which don't require a run loop to run. See https://stackoverflow.com/a/19996367/1271826 for a Objective-C example. See https://stackoverflow.com/a/25952724/1271826 for Swift example.

So, unless creating timers in background thread, just use scheduledTimerWithTimeInterval, and you don't have to worry about manually adding it to a run loop.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044
0

If you are creating the timers using below methods then you will need to schedule the timer into the run loop. These methods are helpful when you want to schedule the time with your custom runloop.

timerWithTimeInterval:invocation:repeats:
timerWithTimeInterval:target:selector:userInfo:repeats

If you want to schedule the timer with current runloop or default runloop then you should use below methods. These methods will schedule the timer in current loop with default mode.

scheduledTimerWithTimeInterval:invocation:repeats:
scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
Apurv
  • 17,116
  • 8
  • 51
  • 67
  • Thanks for this answer, could be worth highlighting that these are static initialisers for `Timer` as it might help someone else. – Leon Mar 15 '23 at 11:56