循环中的异步块

时间:2012-10-10 10:04:39

标签: objective-c ios asynchronous cllocation

如何在循环中管理调用异步块?

我的代码被称为n次:

- (void) convertToCountries:(NSString*)time longitude:(NSString*)lon latitude:(NSString*)lat {


CLLocation *myLocation = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];


[geocoder reverseGeocodeLocation:myLocation
               completionHandler:^(NSArray *placemarks, NSError *error) {
                   NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");

                   if (error){
                       NSLog(@"Geocode failed with error: %@", error);
                       return;
                   }

                   if(placemarks && placemarks.count > 0)
                   {
                       //do something
                       CLPlacemark *topResult = [placemarks objectAtIndex:0];
                       NSString *addressTxt = [NSString stringWithFormat:@"%@, %@ %@,%@ %@", [topResult country],
                                               [topResult subThoroughfare],[topResult thoroughfare],
                                               [topResult locality], [topResult administrativeArea]];
                       NSLog(@"%@",addressTxt);

                       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                       [formatter setDateFormat:@"yyyy-MM-dd"];

                       //Optionally for time zone converstions
                       [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];


                       [DataOperations saveRecord:[topResult country] time:time];

                   }
               }];

}

我需要从这些调用中收集输出数据。

任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

为您的对象提供属性BOOL dunloadin

然后,在完成块中,将self.dunloadin设置为YES

最后,你的循环应该是这样的:

for (int i=0; i<10; i++)
{
    self.dunloadin = NO;
    [self convertToCountries:…];

    while (!self.dunloadin)
    {
        [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
}

但是,您可能需要考虑以不同方式设计您的应用,以便不需要这样的kludges。