好的。爲了幫助他人理解如何處理這種方法,我分享了我自己的代碼。
爲了限制併發線程的數量,我們可以調用-(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];
}
覆蓋的NSOperation
子類的- (void)start
方法來啓動我們的自定義操作:
- (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指着我出去缺少的一部分。
怎麼這個類可以看看滿足這些要求? – voromax 2012-08-09 01:15:19
對於'addDependency:'+1。我真的很想念它。 – voromax 2012-08-09 01:43:09
Rob Napier,你如何在BlockOperations上使用addDependency? – 2014-10-30 20:05:53