iOS 知识小集(5) 发表于 2018-10-18 | 分类于 知识小集 异步方法封装成同步 使用派发组dispatch_group 123456789101112131415161718192021222324- (NSInteger)methodSync { NSLog(@"methodSync 开始"); __block NSInteger result = 0; dispatch_group_t group = dispatch_group_create(); dispatch_group_enter(group); [self methodAsync:^(NSInteger value) { result = value; dispatch_group_leave(group); }]; dispatch_group_wait(group, DISPATCH_TIME_FOREVER); NSLog(@"methodSync 结束 result:%ld", (long)result); return result;} (推荐):使用信号量dispatch_semaphore 1234567891011121314151617181920212223- (NSInteger)methodSync { NSLog(@"methodSync 开始"); __block NSInteger result = 0; dispatch_semaphore_t sema = dispatch_semaphore_create(0); [self methodAsync:^(NSInteger value) { result = value; dispatch_semaphore_signal(sema); }]; // 这里本来同步方法会立即返回,但信号量=0使得线程阻塞 // 当异步方法回调之后,发送信号,信号量变为1,这里的阻塞将被解除,从而返回正确的结果 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); NSLog(@"methodSync 结束 result:%ld", (long)result); return result;}