0

I have an NSTimer that should be running all the time the app is active. It is intended to show a countdown that depends on certain user's actions. I fire this timer this way:

self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(notifyTimerTick:)
                                                userInfo:nil
                                                 repeats:YES];

Then, in the method notifyTimerTick:, I update the countdown label I show to users and, if the countdown is over, I invalidate the timer, I look for a new countdown, and I fire the timer again.

I'm not having troubles being the UI blocked doing this way, but on the other hand, I've found that sometimes the notifyTimerTick: selector call is significantly delayed: I have a view that takes a couple of seconds to be completely loaded, and I've seen that timer's selector is not called until the corresponding view controller's viewDidLoad delegate method is called.

I've read several posts dealing with timers blocking the UI, but I'm not sure how to deal with a timer getting blocked by the UI... what the best way to handle this should be?

Thanks in advance

AppsDev
  • 12,319
  • 23
  • 93
  • 186

1 Answers1

0

You need to use a different run loop mode.

When you use the ScheduledtimerWithTimeInterval class method, the timer is scheduled on the current run loop.

Instead do something like this:

NSTimer *labelTick = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:labelTick forMode:NSRunLoopCommonModes];
Woodstock
  • 22,184
  • 15
  • 80
  • 118
  • Thanks. I've just tested your code, but it still seems that timer's countdown is blocked... could that be because I'm firing the timer within another view controller? Should I better have the timer property declared in `AppDelegate` and handle the timer there? – AppsDev Sep 07 '14 at 18:18
  • Your code is attaching the timer to the main thread, right? Should I fire the timer from a different thread? – AppsDev Sep 07 '14 at 18:33