问题
I have the following bit of code in a class method
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];
}];
}
After execution of this code, I want to return the shopLocations array as a result for the method. However I need to somehow wait until all geocoder searches have finished if I don't want the array to be empty.
How can I do this?
I have tried different GCD approaches, but haven't been successful so far.
回答1:
This can be handled by the dispatch_group_... functions:
…
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);
…
I'm using these kind of blocks to accumulate some network requests.
I hope this can help.
来源:https://stackoverflow.com/questions/9473577/waiting-for-clgeocoder-to-finish-on-concurrent-enumeration