首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >等待CLGeocoder在并发枚举时完成

等待CLGeocoder在并发枚举时完成
EN

Stack Overflow用户
提问于 2012-02-28 06:45:00
回答 1查看 2K关注 0票数 2

我在类方法中有以下几段代码

代码语言:javascript
复制
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方法,但到目前为止还没有成功。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-28 13:48:40

这可以通过dispatch_group_...函数来处理:

代码语言:javascript
复制
…
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);

…

我正在使用这些类型的块来累积一些网络请求。

我希望这能有所帮助。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9473577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档