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.
You should use GCD and
dispatch_afterfor 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_afterit will suggest the snippet and if you validate it will write the prepared 2-3 lines for you in your code 🙂