【发布时间】:2012-12-17 01:46:33
【问题描述】:
我正在使用 NSOperationQueue 来排队和调用一些地理编码位置查找。我想在所有异步运行的查找完成后调用完成方法。
-(void)geocodeAllItems {
NSOperationQueue *geoCodeQueue = [[NSOperationQueue alloc]init];
[geoCodeQueue setName:@"Geocode Queue"];
for (EventItem *item in [[EventItemStore sharedStore] allItems]) {
if (item.eventLocationCLLocation){
NSLog(@"-Location Saved already. Skipping-");
continue;
}
[geoCodeQueue addOperationWithBlock:^{
NSLog(@"-Geocode Item-");
CLGeocoder* geocoder = [[CLGeocoder alloc] init];
[self geocodeItem:item withGeocoder:geocoder];
}];
}
[geoCodeQueue addOperationWithBlock:^{
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
NSLog(@"-End Of Queue Reached!-");
}];
}];
}
- (void)geocodeItem:(EventItem *)item withGeocoder:(CLGeocoder *)thisGeocoder{
NSLog(@"-Called Geocode Item-");
[thisGeocoder geocodeAddressString:item.eventLocationGeoQuery completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"Error: geocoding failed for item %@: %@", item, error);
} else {
if (placemarks.count == 0) {
NSLog(@"Error: geocoding found no placemarks for item %@", item);
} else {
if (placemarks.count > 1) {
NSLog(@"warning: geocoding found %u placemarks for item %@: using the first",placemarks.count,item);
}
NSLog(@"-Found Location. Save it-");
CLPlacemark* placemark = placemarks[0];
item.eventLocationCLLocation = placemark.location;
[[EventItemStore sharedStore] saveItems];
}
}
}];
}
输出
[6880:540b] -Geocode Item-
[6880:110b] -Geocode Item-
[6880:540b] -Called Geocode Item-
[6880:110b] -Called Geocode Item-
[6880:110b] -Geocode Item-
[6880:540b] -Geocode Item-
[6880:110b] -Called Geocode Item-
[6880:540b] -Called Geocode Item-
[6880:110b] -Geocode Item-
[6880:580b] -Geocode Item-
[6880:1603] -Geocode Item-
[6880:110b] -Called Geocode Item-
[6880:1603] -Called Geocode Item-
[6880:580b] -Called Geocode Item-
[6880:907] -End Of Queue Reached!-
[6880:907] -Found Location. Save it-
[6880:907] -Found Location. Save it-
[6880:907] -Found Location. Save it-
[6880:907] -Found Location. Save it-
[6880:907] -Found Location. Save it-
[6880:907] -Found Location. Save it-
[6880:907] -Found Location. Save it-
如您所见,End of Queue 函数在所有地理编码过程 + 保存事件的实际结束之前被调用。只有在处理完所有排队查找时,才应在最后显示“已到达队列结束”。我怎样才能把它变成正确的顺序?
【问题讨论】:
-
-Called Geocode Item-来自哪里?我在代码中没有看到它。 -
您可以在队列中添加观察者。一个好的答案在这里stackoverflow.com/questions/1049001/…
-
我更新了代码。我在发布之前做了一个快速清理并错过了那部分。
-
@BerndPlontsch 我不知道你的最终解决方案是什么,但我最终得出的结论是,如果我想使用
NSOperationQueue,每个地理编码请求需要两个操作,一个用于初始请求,一个用于完成处理程序,我使每个请求都依赖于前一个请求的完成处理程序。见stackoverflow.com/questions/14195706/…
标签: objective-c ios objective-c-blocks nsoperationqueue