iOS: Perform action after time while user is interacting / scrolling

RileyE picture RileyE · Jun 28, 2012 · Viewed 10k times · Source

I'm trying to get my application to perform an action after a delay, but it will have to be done WHILE the user is interacting with/scrolling on a UIScrollView.

I'm not sure why neither performSelector:withObject:afterDelay or scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: will fire. Is it because they're on a background thread?

Any suggestions or help?

Answer

Nikolai Ruhe picture Nikolai Ruhe · Jun 28, 2012

Both NSTimer and performSelector:withObject:afterDelay: by default only fire in the normal run loop mode. When scrolling, the run loop is in event tracking mode.

You have to schedule your timed action in all common modes:

NSTimer *timer = [NSTimer timerWithTimeInterval:0.016 target:self selector:@selector(fire:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

or

[self performSelector:@selector(fire:) withObject:nil afterDelay:1.0 inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];

There's also the dedicated NSEventTrackingRunLoopMode.