好的。为了帮助其他人了解如何处理这种方法,我分享了我自己的代码。
为了限制并发线程的数量,我们可以调用实例的-(void)setMaximimumConcurrentOperationCount:
方法。NSOperationQueue
为了迭代对象并提供完成机制,我们可以定义以下方法:
- (void)enumerateObjects:(NSArray *)objects
{
// define the completion block
NSBlockOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Update UI");
}];
// register dependencies
for (CustomObject *obj in objects) {
CustomOperation *operation = [[CustomOperation alloc] initWithCustomObject:obj];
[completionOperation addDependency:operation]; // set dependencies for the completion block
[_operationQueue addOperation:operation];
}
// register completionOperation on main queue to avoid the cancellation
[[NSOperationQueue mainQueue] addOperation:completionOperation];
}
覆盖子类的- (void)start
方法,NSOperation
开始我们的自定义操作:
- (void)start
{
// We need access to the operation queue for canceling other operations if the process fails
_operationQueue = [NSOperationQueue currentQueue];
if ([self isCancelled]) {
// Must move the operation to the finished state if it is canceled.
[self willChangeValueForKey:@"isFinished"];
_finished = YES;
[self didChangeValueForKey:@"isFinished"];
return;
}
[self willChangeValueForKey:@"isExecuting"];
// We do not need thread detaching because our `-(void)processWithCompletionBlock:` method already uses dispatch_async
[self main]; // [NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
_executing = YES;
[self didChangeValueForKey:@"isExecuting"];
}
覆盖子类的- (void)main
方法NSOperation
来处理我们的自定义对象:
- (void)main
{
@try {
NSLog(@"Processing object %@", _customObject);
[_customObject processWithCompletionBlock:^(BOOL success) {
_processed = success;
if (!success) {
NSLog(@"Cancelling other operations");
[_operationQueue cancelAllOperations];
}
[self completeOperation];
}];
}
@catch (NSException *exception) {
NSLog(@"Exception raised, %@", exception);
}
}
感谢@Rob 指出我缺少的部分。