Waiting for CLGeocoder to finish on concurrent enumeration

左心房为你撑大大i 提交于 2020-01-02 09:55:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!