ios - NSBlockOperation 在执行之前不等待依赖
<p><p>我正在学习 <code>NSOperations</code> 和 <code>NSOperationQueue</code>。</p>
<p>我有一组 <code>NSBlockOperation</code>:“<em>上传</em>”和“<em>DELETE</em>”。删除<strong><em>必须</em></strong>等待上传完成后再执行。</p>
<p>我希望在进行下一组操作之前完成一组操作。</p>
<p>我已经使用 <code>NSThread sleepForTimeInterval</code> 来模拟上传等待和删除延迟时间。</p>
<p>但是这些操作并没有等待集合完成。</p>
<p>我将 <code>maxConcurrentOperationCount</code> 设置为 1,但这似乎不起作用。</p>
<p>您可以从输出中看到 Set 1 完成得很好。</p>
<p>但是在 <strong><em>Delete 2</em></strong> 完成之前,第二组 <strong><em>Upload 3</em></strong> 就盯着看。然后上传/删除 4 就可以了。然后从那里开始变得更加困惑。</p>
<p><strong><em>有什么帮助吗?</em></strong></p>
<p><strong>输出:</strong></p>
<pre><code>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></pre>
<p><strong>代码:</strong></p>
<pre><code>- (void)viewDidLoad {
;
NSOperationQueue *operationQueue = ;
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 = ;
NSOperation * DELETE = ;
;
;
;
}
}
- (NSBlockOperation *) createNewOperationWithInt:(int)i Message:(NSString*)message {
NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Start %@ %i",message , i);
if () {
; //Pretend there is Network latency on upload
}
if () {
; //Pretend the SQLDB is being accessed
}
}];
operation.queuePriority = NSOperationQueuePriorityNormal;
operation.qualityOfService= NSOperationQualityOfServiceUtility;
operation.completionBlock = ^{
NSLog(@"Completed %@ %i",message , i);
};
return operation;
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这种行为似乎很好。 “问题”是完成 block 和依赖项都在 <em>upload</em> 任务完成后运行。这就是为什么您有时会在“完成上传 N”之前得到“开始删除 N+1”。</p>
<p>尝试在 block 操作结束时添加一条消息,以检查它是否在开始下一个操作之前完成:</p>
<pre><code>NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Start %@ %i",message , i);
if () {
; //Pretend there is Network latency on upload
}
if () {
; //Pretend the SQLDB is being accessed
}
NSLog(@"Finished %@ %i",message , i);
}];
</code></pre></p>
<p style="font-size: 20px;">关于ios - NSBlockOperation 在执行之前不等待依赖,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/43545417/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/43545417/
</a>
</p>
页:
[1]