iosuiscrollviewperformselector

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


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?


Solution

  • 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.