Created
January 20, 2012 22:57
-
-
Save bjhomer/1650079 to your computer and use it in GitHub Desktop.
Waiting on asynchronous results without blocking the run loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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