Question

I have a need to delay for a certain amount of time and yet allow other things on the same runloop to keep running. I have been using the following code to do this:

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];

This seems to do exactly what I want, except that sometimes the function returns immediately without waiting the desired time (1 second).

Can anyone let me know what could cause this? And what is the proper way to wait while allowing the run loop to run?

NOTE: I want to delay in a manner similar to sleep(), such that after the delay I am back in the same execution stream as before.

Was it helpful?

Solution

You should use GCD and dispatch_after for that. It is much more recent and efficient (and thread-safe and all), and very easy to use.

There is even a code snippet embedded in Xcode, so that if you start typing dispatch_after it will suggest the snippet and if you validate it will write the prepared 2-3 lines for you in your code :)

Code Snippet suggestion by Xcode

int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    <#code to be executed on the main queue after delay#>
});

OTHER TIPS

Use an NSTimer to fire off a call to some method after a certain delay.

Have you tried performSelector:withObject:afterDelay:?

From the Apple documentation

Invokes a method of the receiver on the current thread using the default mode after a delay.

I had a similar issue and this is my solution. Hope it works for others as well.

__block bool dispatched = false;
while ( put your loop condition here )
{
    if (dispatched)
    {
        // We want to relinquish control if we are already dispatched on this iteration.
        [ [ NSRunLoop currentRunLoop ] runMode: NSDefaultRunLoopMode beforeDate:[ NSDate date ] ];
        continue;
    }

    // mark that a dispatch is being scheduled
    dispatched = true;

    int64_t delayInNanoSeconds = (int64_t) (0.1 * (float) NSEC_PER_SEC);
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, delayInNanoSeconds);

    dispatch_after(delayTime, dispatch_get_main_queue(), ^() {
       // Do your loop stuff here
       // and now ready for the next dispatch
       dispatched = false;
    } );
}  // end of while 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top