Skip to content

Instantly share code, notes, and snippets.

@bjhomer
Created January 20, 2012 22:57
Show Gist options
  • Save bjhomer/1650079 to your computer and use it in GitHub Desktop.
Save bjhomer/1650079 to your computer and use it in GitHub Desktop.
Waiting on asynchronous results without blocking the run loop
// This is a useful bit of code for waiting for the results of an
// asynchronous operation. It's especially useful in unit tests.
// It keeps the run loop going, so it's not blocking delegate callbacks.
BOOL waitForBlock(NSTimeInterval timeout,
BOOL (^condition)(void)) {
NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeout];
BOOL val = condition();
while ( val == NO && [timeoutDate timeIntervalSinceNow] > 0 ) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeoutDate];
val = condition();
}
return val;
}
// Use like this:
__block id someObject = nil;
[self doSomethingAsynchronousWithBlock:^(id theResult) {
someObject = theResult;
}];
BOOL succeeded = waitForBlock(5, ^{ return someObject != nil; });
// if succeeded == NO, then the block never returned YES
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment