2

我在學習NSOperations & NSOperationQueueNSBlockOperation在執行前不等待依賴關係

我有一組NSBlockOperation: 「上傳」 & 「DELETE」。刪除必須等待上傳完成後再執行。

我想要發生的是在進行下一組前完成一項操作。

我已經使用NSThread sleepForTimeInterval來模擬上傳等待和刪除延遲時間。

但是,操作並未等待設置完成。

我將maxConcurrentOperationCount設置爲1,但似乎不起作用。

您可以從輸出中看到Set 1完成正常。

但在組兩個上傳3盯着刪除2結束了。然後上傳/刪除4是好的。然後從那裏開始混淆更多。

任何幫助?

OUTPUT:

Start UPLOAD 1 
Completed UPLOAD 1 
Start DELETE 1 
Completed DELETE 1 

Start UPLOAD 2 
Completed UPLOAD 2 
Start DELETE 2 
Start UPLOAD 3 
Completed DELETE 2 
Start DELETE 3 
Completed UPLOAD 3 
Completed DELETE 3 

Start UPLOAD 4 
Start DELETE 4 
Completed UPLOAD 4 
Completed DELETE 4 

Start UPLOAD 5 
Start DELETE 5 
Completed UPLOAD 5 
Start UPLOAD 6 
Completed DELETE 5 
Start DELETE 6 
Completed UPLOAD 6 
Start UPLOAD 7 
Completed DELETE 6 

CODE:

- (void)viewDidLoad { 
    [super viewDidLoad]; 


    NSOperationQueue *operationQueue = [NSOperationQueue mainQueue]; 
    operationQueue.maxConcurrentOperationCount = 1; 


//pretend there are 100 images that need to be uploaded and information in a SQLite DB waiting to be deleted upon successful upload of the image. 

//Upload 1 image at a time, upon successful upload, delete the respective DB info then move to the next image 
    for (__block int i = 1; i < 100; i++){ 
     NSOperation * UPLOAD = [self createNewOperationWithInt:i Message:@"UPLOAD"]; 
     NSOperation * DELETE = [self createNewOperationWithInt:i Message:@"DELETE"]; 
     [DELETE addDependency:UPLOAD]; 
     [operationQueue addOperation:UPLOAD]; 
     [operationQueue addOperation:DELETE]; 

    } 

} 

- (NSBlockOperation *) createNewOperationWithInt:(int)i Message:(NSString*)message { 
    NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{ 
     NSLog(@"Start %@ %i",message , i); 

     if ([message containsString:@"UPLOAD"]) { 
      [NSThread sleepForTimeInterval:1]; //Pretend there is Network latency on upload 
     } 

     if ([message containsString:@"DELETE"]) { 
      [NSThread sleepForTimeInterval:0.5]; //Pretend the SQLDB is being accessed 
     } 

    }]; 
    operation.queuePriority = NSOperationQueuePriorityNormal; 
    operation.qualityOfService = NSOperationQualityOfServiceUtility; 
    operation.completionBlock = ^{ 
     NSLog(@"Completed %@ %i",message , i); 
    }; 

    return operation; 
} 
+2

閱讀NSOperation'的''的屬性completionBlock'的文檔。這個討論解釋了你的輸出。 – rmaddy

回答

3

這種行爲似乎是罰款。 「問題」是在完成上傳任務之後,完成塊和依賴項都運行。這就是爲什麼您有時在「完成上傳N」之前獲得「開始刪除N + 1」的原因。

嘗試在塊操作結束添加消息,以檢查它是否開始下一個之前完成:

NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{ 
    NSLog(@"Start %@ %i",message , i); 

    if ([message containsString:@"UPLOAD"]) { 
     [NSThread sleepForTimeInterval:1]; //Pretend there is Network latency on upload 
    } 

    if ([message containsString:@"DELETE"]) { 
     [NSThread sleepForTimeInterval:0.5]; //Pretend the SQLDB is being accessed 
    } 

    NSLog(@"Finished %@ %i",message , i); 
}];