In the UIViewController
, I have an NSTimer
scheduled to fire every 1 second, using scheduledTimer
method, so I could update a UILabel
in the view every second. But the problem is, the NSTimer
firing seemed to be delayed whenever I pan around the MKMapView
that is inside also inside the UIView
. So the delay results in the UILabel
not updating uniformly, which is not good to see. Could the delay caused by MKMapView
panning taking too much resources? How could I schedule the NSTimer
so that there is no delay however I pan the MKMapView
? (Note, however, that I didn't schedule the NSTimer
on some kind of background thread, it is in the main thread.) Thanks.
Asked
Active
Viewed 135 times
1

Dharmesh Dhorajiya
- 3,976
- 9
- 30
- 39

Blip
- 1,158
- 1
- 14
- 35
-
Does setting up the timer in the background thread to do the calculation, then using `dispatch_async` code to get main thread to update the UI, work ? The dispatch_async example is shown in this asnwer: http://stackoverflow.com/questions/16283652/understanding-dispatch-async – Zhang Apr 04 '15 at 13:19
-
How are you scheduling the timer? You need to schedule it with `NSRunLoopCommonModes` if you want it to fire while scrolling/panning. – dan Apr 04 '15 at 14:00
1 Answers
4
If you use scheduledTimerWithTimeInterval(...)
to create your timer, it will be added to the current runloop with mode NSDefaultRunLoopMode
. The timer will not fire while your app is busy with event tracking, i.e. if you scroll around in a UIScrollView or if you do any other interactions with your UI.
You can create a unscheduled NSTimer and add it to the runloop yourself, if you use NSRunLoopCommonModes
as mode the timer will fire while you interact with the user interface.
let timer = NSTimer(timeInterval: 1.0, target: self, selector: Selector("timerFired:"), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
For further information, the question NSDefaultRunLoopMode vs NSRunLoopCommonModes contains a nice explanation about the different runloop modes.

Community
- 1
- 1

Matthias Bauch
- 89,811
- 20
- 225
- 247
-
Thanks, but there is a problem...the app registers for background location updates, and the CLLocationManager I use to get location updates is defer-updates-enabled. I tried to add the timer to the run loop with NSRunLoopCommonModes, but it seems that the system kills the app when it runs for too long. I think it is because the NSTimer is taking up NSRunLoop when the run loop should be inactivated. – Blip Apr 04 '15 at 21:44
-
so invalidate the timer if the app goes into the background, and recreate it when the app comes into the foreground again – Matthias Bauch Apr 05 '15 at 10:45
-