Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a NSTimer always be added into a runloop to execute

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?

like image 854
Xin Yuan Avatar asked Jun 03 '14 13:06

Xin Yuan


1 Answers

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.

like image 169
Rob Avatar answered Sep 27 '22 19:09

Rob