2013-06-22 42 views
0

我異步下載了一些對象,我將它存儲在數組中。接下來爲每個對象下載一些帶有地理編碼的座標(它也是異步的),並使用座標爲新的參數更新每個對象的數據庫。我的方法是這樣的:如何等待所有異步任務?

- (void)downloadObjectsWithTitle:(NSString *)title andHandler:(void(^)(NSMutableDictionary *result))handler { 
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" 
                 path:nil 
                parameters:nil]; 
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]]; 
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     //I get here array of objects 
     //now for each object I want to download geocoding localization so i called another asynchronyous method getLocationWithTitle:andHandler; 
     for(int i = 0; i < resutArray.count; i++) { 
      [self downloadLocationWithString:[dictionary objectForKey:@"string"] andHandler:^(NSMutableDictionary *result) { 
       //update database; 
      }]; 
     } 
     handler(dictionary); 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"Error: %@", error); 
    }]; 
    [operation start]; 
} 

我的問題是如何downalod每個對象的座標和火:戒菸方法之前

handler(dictionary); 

所以等待每個座標下載(每個對象)(火處理程序)。

Thnaks for all sugestions。

回答

1

維護所有任務的計數。當它爲零時,你就完成了。

0

嘗試一個全局標誌。首先設置NO。在下載完成後,將完成設置標誌設置爲yes。你可以檢查那個標誌。你在使用downloadLocationWithString:dispatch_async併發隊列

+0

如果我只有一個要求進行地理編碼,這種情況就沒有問題。但對於多它不會工作。 – edzio27

+0

採用全局變量並將其分配總數。只要下載完成,只需將變量減1即可。如果其值爲0,則所有的下載都完成,您可以檢查該變量的值。 – keen

1

假設:

dispatch_barrier_async(queue, ^{ 
    // will only be called after all the blocks submitted to queue have finished. 
}]; 

(如果你使用的串行隊列,只需調用處理程序在最後一個塊的最後一行)