这里的目标是将异步操作转换为同步操作。最常用的方法是使用信号量。
- (void)testAnimationResult {
// Create a semaphore object
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[UIView animateWithDuration:1.5 animations:^{
// Some animation
} completion:^(BOOL finished) {
// Signal the operation is complete
dispatch_semaphore_signal(sem);
}];
// Wait for the operation to complete, but not forever
double delayInSeconds = 5.0; // How long until it's too long?
dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
long timeoutResult = dispatch_semaphore_wait(sem, timeout);
// Perform any tests (these could also go in the completion block,
// but it's usually clearer to put them here.
XCTAssertTrue(timeoutResult == 0, @"Semaphore timed out without completing.");
XCTAssertTrue(1 == 0, @"Error: 1 does not equal 0, of course!");
}
如果您想查看一些实际示例,请查看RNCryptorTests。