MyOperation *operation = [MyOperation alloc] init]; NSOperationQueue* aQueue = [[NSOperationQueue alloc] init]; [aQueue addOperation:operation];我們也可以直接通過NSOpeartion的start方法來處理operation任務,這樣執行的話任務的處理是在start調用的線程中同步執行的。
MyOperation *operation = [MyOperation alloc] init]; [operation start];isConcurrent屬性返回的就是operation要執行的任務相對於調用start的線程是同步的還是異步的,isConcurrent默認返回NO。當然我們也可以自己創建線程來執行NSOperation的start方法達到並發執行的效果。
@implementation MyCustomClass - (NSOperation*)taskWithData:(id)data { NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myTaskMethod:) object:data]; return theOp; } // This is the method that does the actual work of the task. - (void)myTaskMethod:(id)data { // Perform the task. } @end
NSBlockOperation* theOp = [NSBlockOperation blockOperationWithBlock: ^ { NSLog(@"Beginning operation.\n"); // Do some work. }];NSBlockOperation可以通過addExecutionBlock:方法添加多個block,只有所有block都執行完成的時候,operation才算是完成。
@interface MyOperation : NSOperation { BOOL executing; BOOL finished; } - (void)completeOperation; @end @implementation MyOperation - (id)init { self = [super init]; if (self) { executing = NO; finished = NO; } return self; } - (void)start { // Always check for cancellation before launching the task. if ([self isCancelled]) { // Must move the operation to the finished state if it is canceled. [self willChangeValueForKey:@"isFinished"]; finished = YES; [self didChangeValueForKey:@"isFinished"]; return; } // If the operation is not canceled, begin executing the task. [self willChangeValueForKey:@"isExecuting"]; [self main]; executing = YES; [self didChangeValueForKey:@"isExecuting"]; } - (void)main { @autoreleasepool { BOOL isDone = NO; while (![self isCancelled] && !isDone) { // Do some work and set isDone to YES when finished } [self completeOperation]; } } - (void)completeOperation { [self willChangeValueForKey:@"isFinished"]; [self willChangeValueForKey:@"isExecuting"]; executing = NO; finished = YES; [self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isFinished"]; } - (void)cancel { [super cancel]; //取消網絡請求 } - (BOOL)isConcurrent { return YES; } - (BOOL)isExecuting { return executing; } - (BOOL)isFinished { return finished; } @end並發operation需要實現以下方法:
我們可以通過setThreadPriority:設置operation系統級別的線程優先級,優先級由0.0到1.0浮點數指定,默認是0.5。我們自己設置的系統級別的線程優先級只針對main方法執行期間有效,其他方法都是按照默認優先級執行。
參考鏈接:Concurrency Programming Guide