我正在尝试排队多个异步请求以将数据加载到某些对象中。我需要按顺序执行它们并等待每个对象loadDataWithCompletion
在下一个对象启动之前被触发。
为每个对象加载所有数据后,将检查该对象以查看数据是否有效。
如果对象被标记为有效,则将其添加到临时数组中,然后下一个对象应执行它的loadData
方法并重复此过程。
由于每个对象的loadData
方法都是异步的,并且completionBlock
可能几秒钟没有被调用,我需要确保最后operationBlock
用于复制临时数组在所有对象完成loadDataWithCompletion
和isValid
检查之前,最后一个未被解雇。
但是,现在,在每个对象的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];
}
}