2014-02-18 44 views
1

當前我正在嘗試執行一些異步和併發任務,並且我使用Azure blob來上傳所有圖像,但是擔心的是,對於每個blob,我需要獲取SASURL,然後上傳圖像。另一方面,我希望完成的圖像的所有操作都要上傳,並最終上傳到數據庫。雖然我可以提前將操作發送到數據庫,但沒有完成對圖像的確認,但我只是想確保操作完成。for循環中的完成塊

下面是SASURL塊的代碼。

- (void)storageServiceBlob:(NSArray*)images 
{ 
    StorageService *storageService = [StorageService getInstance]; 
    NSLog(@"%@",[storageService containers]); 
    NSLog(@"%@",[storageService blobs]); 

    for (int i = 0; i < [images count]; i++) { 

     NSString *file_name = [images objectAtIndex:i]; 
     NSString *result = [self imageName:file_name]; 
     NSLog(@"Final: %@", result); 

     [storageService getSasUrlForNewBlob:result forContainer:@"misccontainer" withCompletion:^(NSString *sasUrl) { 

      NSLog(@"%@",sasUrl); 
      [self postBlobWithUrl:sasUrl Image:[images objectAtIndex:i]]; 
     }]; 
    } 
} 

我想在組使用GCD某種方式來確定全部完成塊被稱爲一組後,它執行Post方法。無論如何gcd做到這一點?

+0

當'completedBlocks == [images count]'時,您可以在完成塊中保持運行總數並運行您的郵政編碼。 – Linuxios

回答

4

還有許多你可以做到這一點。這裏有一個:

- (void)storageServiceBlob:(NSArray *)imageFilenames 
{ 
    StorageService *storageService = [StorageService getInstance]; 
    __block NSMutableSet *remainingImageFilenames = [NSMutableSet setWithArray:imageFilenames]; 

    for (NSString *imageFilename in imageFilenames) { 
     NSString *imageName = [self imageNameForImageFilename:imageFilename]; 

     [storageService getSasUrlForNewBlob:imageName forContainer:@"misccontainer" withCompletion:^(NSString *sasUrl) { 
      [self postBlobWithUrl:sasUrl imageFilename:imageFileName]; 
      [remainingImageFilenames removeObject:imageFilename]; 
      if ([remainingImageFilenames count] == 0) { 
       // you're done, do your thing 
      } 
     }]; 
    } 
} 

一些提示:

  • 小心你的命名。那裏似乎有些模棱兩可。

  • 通常,慣用方法名稱參數以小寫字母開頭,例如, myMethodWithThis:andThat:,而不是MyMethodWithThis:AndThat:

  • 快速枚舉,例如for (id obj in array)是你的朋友。學習和使用它。

  • 您可以將快捷方式[array objectAtIndex:1]設爲array[1]

1

如果您有權訪問請求進入的隊列,則可以發出障礙塊。

當你有一個異步隊列時,一個障礙塊會坐下來等待執行,直到所有在它之前發出的塊都運行完畢。

如果你沒有進入隊列,那麼你最好的選擇是保持計數。