Skip to content

Instantly share code, notes, and snippets.

@BenedictC
Created January 26, 2014 12:05
Show Gist options
  • Save BenedictC/8631726 to your computer and use it in GitHub Desktop.
Save BenedictC/8631726 to your computer and use it in GitHub Desktop.
Functions for running the run loop during tests with Xcode.
/*
Functions for firing a runloop while performing asynchronous tests. Add them at the top of the .m file.
-(void)testExample {
__block NSInteger count = 0;
dispatch_async(dispatch_get_main_queue(), ^{
count = 1;
});
WAIT_FOR(0.1);
XCTAssert(count == 1, "Async block did not execute.");
}
*/
#pragma mark - async functions
static void WAIT_ON_CONDITION(BOOL(^condition)(void), NSTimeInterval relativeTimeout) {
NSTimeInterval absoluteTimeout = [NSDate timeIntervalSinceReferenceDate] + relativeTimeout;
while (!condition()) {
BOOL didTimeout = absoluteTimeout < [NSDate timeIntervalSinceReferenceDate];
if (didTimeout) return;
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
}
static void WAIT_FOR(NSTimeInterval relativeTimeout) {
NSTimeInterval absoluteTimeout = [NSDate timeIntervalSinceReferenceDate] + relativeTimeout;
WAIT_ON_CONDITION(^BOOL{
return absoluteTimeout < [NSDate timeIntervalSinceReferenceDate];
}, relativeTimeout);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment