Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to my NSRunLoop and timer when the app goes into background and returns?

I have an NSRunLoop in my app connected to a timer:

NSTimer *updateTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(onUpdateTimer) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:updateTimer forMode:NSRunLoopCommonModes];

When the app goes into background, what happens to this runloop? Does it disappear, meaning I should recreate it in applicationDidBecomeActive:?

like image 661
dgund Avatar asked Jun 22 '12 20:06

dgund


People also ask

Does NSTimer run in background?

Problem is, NSTimer requires an active run loop which is not always readily available on background queues. The main thread has an active run loop but this defeats the purpose of having our timer run in the background so its a definite no go. So, to get a dedicated background-queue-friendly timer, we use GCD.


1 Answers

You should stop your timers when your app is suspended and restart them in -applicationDidBecomeActive:. See "What to Do When an Interruption Occurs" in Responding to Interruptions. You don't have to worry about the run loop, though -- the OS will take care of that part.

like image 114
Caleb Avatar answered Nov 02 '22 23:11

Caleb