2012-10-10 144 views
0

如何管理在循環中調用異步塊?循環中的異步塊

我的代碼被稱爲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]; 

        } 
       }]; 

} 

我需要從這些電話收集輸出數據。

任何幫助將不勝感激。

+0

你有什麼問題? – sergio

+0

由於它是異步調用,它不會等待處理結果,然後繼續。循環只用第一個參數完成。 – Vanya

+0

你會怎麼做?對呼叫進行排序(例如,等待一個完成,並使用結果)? – sergio

回答

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]]; 
    } 
} 

但是,您可能希望使不需要這樣的組裝機來考慮不同的設計您的應用程序。

+0

工作得很好,thx。 – Vanya