Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is adding Timer to main RunLoop the right solution?

Tags:

ios

swift

timer

I have a Timer that I want to continuously repeat at a given interval, however the only way I can seem to get the Timer to persist is by adding it to RunLoop.main like below:

let timer = Timer(timeInterval: timeInterval, repeats: true) { (timer) in
    blockToFire()
}
RunLoop.main.add(timer, forMode: .commonModes)

I understand that using .commonModes should prevent the timer from missing its cue when a user interacts with the UI, but will the timer cause problems being added to the main run loop? Will there be UI slow downs?

like image 290
DranoMax Avatar asked Oct 26 '18 00:10

DranoMax


1 Answers

The code you posted is fine. A runloop is associated with a particular thread. Timers are usually run on the main thread/main runloop. As such, they will cause "hiccups" in the main thread if their code takes too long to execute. Don't invoke blocks/selectors who's code takes a long time to run from the main thread/attach them to the main run loop, or you will cause a UI slowdown.

You can also create and run a timer on a background thread. I generally use one of the scheduledTimer() methods, which creates a timer and adds it to the "current run loop" (which means the run loop for the current thread.)

If you want to run a timer on a different thread, you can call one of the scheduledTimer() methods from your background thread. However beware that you should not make UIKit calls from a background thread.

like image 66
Duncan C Avatar answered Oct 02 '22 17:10

Duncan C