如何先执行block中的代码后在执行下面的代码
一.问题
-(CLPlacemark*)getStartplacemark
{
__block CLPlacemark* start;
[ self.geoCoder geocodeAddressString:_SourceText.text completionHandler:^(NSArray*placemarks, NSError*error) {
CLPlacemark *startPlaceMark=[placemarks firstObject];
start=startPlaceMark;
}];
NSLog(@"%@",start);//这里打印出的是一个 null,是因为 block 是异步的,所以会先走下面的 return,
returnstart;
}
二.解决方法
- (CLPlacemark*)getStartplacemark
{
//先创建一个semaphore
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
__block CLPlacemark* start;
[self.geoCoder geocodeAddressString:_SourceText.text completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *startPlaceMark = [placemarks firstObject];
start = startPlaceMark;
//发出已完成的信号
dispatch_semaphore_signal(semaphore);
}];
//等待执行,不会占用资源
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return start;
}