gpt4 book ai didi

ios5 - 等待 CLGeocoder 完成并发枚举

转载 作者:行者123 更新时间:2023-12-02 08:49:35 25 4
gpt4 key购买 nike

我在类方法中有以下代码

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


我正在使用这些 block 来积累一些网络请求。

希望对您有所帮助。

关于ios5 - 等待 CLGeocoder 完成并发枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9473577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com