Scheduling Events Not Blocked by User Interface on iOS

Just decided to make a quick post on this, because it had been causing me issues for a few hours now.

In iOS, we generally schedule a repeating timer as follows:

[NSTimer scheduledTimerWithTimeInterval: 0.5 target: self selector: @selector(update) userInfo: nil repeats: YES];

The problem with this is that, UI events (for example, scrolling a UIScrollView, and other animations) prevent the timer from firing. This is because scheduleTimerWithInterval places the timer event in the current run loop, generally NSDefaultRunLoopMode.

The following code will schedule the timer in all common modes, which include the NSDefaultRunLoopMode, and the UITrackingRunLoopMode (which becomes active during touch-tracking events).

NSTimer* timer = [NSTimer timerWithTimeInterval: 0.5 target: self selector: @selector(update) userInfo: nil repeats: YES];
[[NSRunLoop mainRunLoop] addTimer: timer forMode: NSRunLoopCommonModes];

This can be useful, for example, to keep OpenGL rendering when user interaction is occurring with UIKit elements.

No comments:

Post a Comment