等待ClakeoDer完成并发枚举
-
13-11-2019 - |
题
我在类方法中具有以下位代码
NSDictionary *shopAddresses = [[NSDictionary alloc] initWithContentsOfFile:fileName];
NSMutableArray *shopLocations = [NSMutableArray arrayWithCapacity:shopAddresses.count];
[shopAddresses enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id key, ShopLocation *shopLocation, BOOL *stop) {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:shopLocation.address completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"Geocode failed with error: %@", error);
}
else {
shopLocation.placemark = [placemarks objectAtIndex:0];
}
[shopLocations addObject:shopLocation];
}];
}
.
执行此代码后,我希望返回ShopLocations数组,结果是该方法。但是,如果我不希望将数组为空,我需要以某种方式等待所有地理域搜索完成。
如何这样做?
我尝试过不同的GCD方法,但到目前为止还没有成功。
解决方案
这可以由 dispatch_group _... 函数:
.
…
dispatch_group_t group = dispatch_group_create();
[shopAddresses enumerateObjectsUsingBlock:^(id key, NSUInteger idx, BOOL *stop) {
dispatch_group_enter(group);
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:shopLocation.address completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"Geocode failed with error: %@", error);
}
else {
shopLocation.placemark = [placemarks objectAtIndex:0];
}
[shopLocations addObject:shopLocation];
dispatch_group_leave(group);
}];
}];
while (dispatch_group_wait(group, DISPATCH_TIME_NOW)) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.f]];
}
dispatch_release(group);
…
我正在使用这些块来累积一些网络请求。
我希望这可以帮助。