Ios5 正在等待CLGeocoder完成并发枚举

Ios5 正在等待CLGeocoder完成并发枚举,ios5,grand-central-dispatch,clgeocoder,Ios5,Grand Central Dispatch,Clgeocoder,我在一个类方法中有以下代码 NSDictionary *shopAddresses = [[NSDictionary alloc] initWithContentsOfFile:fileName]; NSMutableArray *shopLocations = [NSMutableArray arrayWithCapacity:shopAddresses.count]; [shopAddresses enumerateKeysAndObjectsWithOptions:NSEnumerati

我在一个类方法中有以下代码

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_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);

…
我用这些块来积累一些网络请求


我希望这能有所帮助。

这很容易。我没有想过手动使用调度组。这是我尝试过的解决方案之一,但没有成功。调度组等待函数一直在等待。我认为这是因为dispatch\u group\u leave函数嵌套在completion handler块中,它应该永远等待。但是我刚刚意识到,
-geocodeAddressString:completionHandler:
方法正在主线程上运行块。我的解决方案可能会停止运行循环。但也有一个解决方案,我将编辑上面的答案。是否可以让
dispatch\u group\u wait
只等待有限的时间?我尝试在没有while循环的情况下使用它,并指定了
5.0f
而不是
DISPATCH\u TIME\u NOW
,它似乎根本没有等待。您是否使用
DISPATCH\u TIME()
来创建等待时间?超时是以纳秒为单位指定的,因此5.0f与
DISPATCH\u NOW
相比毫无意义。