前段时间写工厂测试程序,遇到个小问题,就是在发测试命令时,由于回调函数是个block,而block是异步处理的。导致结果无法及时返回。
查看资料后,我是这么处理的
#define TestNeedsToWaitForBlock() __block BOOL blockFinished = NO #define BlockFinished() blockFinished = YES #define WaitForBlock() while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) && !blockFinished)
- (void)setAndGetStepGoal:(int)goal { NSLog(@"测试设置运动目标值:%d", goal); { TestNeedsToWaitForBlock(); [CommandInterface setSteps:goal completion: ^(BOOL success, NSDictionary *info) { BlockFinished(); }]; WaitForBlock(); } { TestNeedsToWaitForBlock(); [CommandInterface getGoal: ^(BOOL success, NSDictionary *info) { int deviceGoal = [info[@"steps"] intValue]; NSLog(@"设置运动目标值结果:%d>>>>>>%d", goal, deviceGoal); XCTAssertEqual(goal, deviceGoal, @"goal与期望不符"); BlockFinished(); }]; WaitForBlock(); } }
原理其实很简单,使用 CFRunLoopRunInMode,阻止线程退出,等待系统消息。
时间: 2024-10-12 16:34:56