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