同步进程执行的同步

我有一些并行操作的数据处理。 在处理过程中,我需要检索该位置的反向地理编码。 据了解, - (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler还在后台线程中执行地理编码请求,并在调用后立即返回。 当地理编码完成请求时,它会在主线程上执行完成处理程序。 我怎样才能阻止我的并发操作,直到geocoder检索结果?

 __block CLPlacemark *_placemark - (NSDictionary *)performDataProcessingInCustomThread { NSMutableDictionary *dict = [NSMutableDictionary alloc] initWithCapacity:1]; // some operations CLLocation *location = [[CLLocation alloc] initWithLatitude:40.7 longitude:-74.0]; [self proceedReverseGeocoding:location]; // wait until the geocoder request completes if (_placemark) { [dict setValue:_placemark.addressDictionary forKey:@"AddressDictionary"]; return dict; } - (void)proceedReverseGeocoding:(CLLocation *)location { CLGeocoder *geocoder = [[CLGeocoder alloc] init]; [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { if ([error code] == noErr) { _placemark = placemarks.lastObject; } }]; } 

为了达到这个目的,我们可以使用dispatch_semaphore_t 。 首先,我们需要给课堂增加信号量:

 dispatch_semaphore_t semaphore; 

当我们正在处理数据并准备接收地理编码数据时,我们应该创build调度信号并开始等待一个信号:

 semaphore = dispatch_semaphore_create(0); [self proceedReverseGeocoding:location]; dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 

在CLGeocodeCompletionHandler的最后,我们只需要发送信号来恢复数据处理:

 dispatch_semaphore_signal(semaphore); 

之后数据处理将继续