iOS - NSOperationQueue没有按顺序触发

时间:2016-10-13 18:04:49

标签: ios asynchronous synchronization nsoperationqueue

我正在尝试排队多个异步请求以将数据加载到某些对象中。我需要按顺序执行它们并等待每个对象loadDataWithCompletion在下一个对象启动之前被触发。

为每个对象加载所有数据后,将检查该对象以查看数据是否有效。 如果对象被标记为有效,则将其添加到临时数组中,然后下一个对象应执行它的loadData方法并重复此过程。

由于每个对象的loadData方法都是异步的,并且completionBlock可能几秒钟没有被调用,我需要确保最后operationBlock用于复制临时数组在所有对象完成loadDataWithCompletionisValid检查之前,最后一个未被解雇。

但是,现在,在每个对象的completionOperation方法中的任何completionBlock被触发之前,最终loadDataWithCompletion块被触发。 (已通过调试器和断点验证)

关于如何确保我的所有异步数据加载的任何建议都会在completionOperation被触发之前被触发并完成?

这是我目前的代码:

- (void)loadCustomObjectsWithCompletion:(void (^)())completionBlock
        if (self.operationQueue) {
            [self.operationQueue cancelAllOperations];
        }

        NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
        operationQueue.maxConcurrentOperationCount = 1;
        self.operationQueue = operationQueue;
        NSOperation *previousOperation;

        NSMutableArray *validObjects = [[NSMutableArray alloc] init];
        for (CustomObject *customObject in self.myCustomObjects) {
            NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                    [customObject loadDataWithCompletion:^{
                        if (customObject.isValid) {
                            [validObjects addObject:customObject];
                        }
                }];
            }];
            if (previousOperation) {
                [operation addDependency:previousOperation];
            }
            [operationQueue addOperation:operation];
            previousOperation = operation;
        }

        NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
            self.validObjects = validObjects;

            if (completionBlock) {
                completionBlock();
            }
        }];

        if (previousOperation) {
            [completionOperation addDependency:previousOperation];
        }
        [operationQueue addOperation:completionOperation];
    }
}

0 个答案:

没有答案