为什么要用NSOperation?为什么不用GCD
在我认为NSOperation的优点是可控制性的,可以随时断开,暂停线程
1 NSBlockOperation *operationA = [NSBlockOperation blockOperationWithBlock:^{ 2 for (int i = 0; i<100; i++) { 3 NSLog(@"-operation-下载图片-%@",[NSThread currentThread]); 4 } 5 }]; 6 7 operationA.completionBlock = ^{ 8 NSLog(@"--开始下载第二张图片--%@",[NSThread currentThread]); 9 }; 10 11 NSLog(@"--现在在干嘛--%@",[NSThread currentThread]); 12 13 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 14 [queue addOperation:operationA];
NSOperation添加线程依赖
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationA:) object:nil]; NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationB:) object:nil]; NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{ for (int i = 0; i<10; i++) { NSLog(@"NSBlockoperation3=--1-----%@",[NSThread currentThread]); } }]; [operation3 addExecutionBlock:^{ for (int i = 0; i<10; i++) { NSLog(@"NSBlockoperation3=--2-----%@",[NSThread currentThread]); } }]; //添加依赖 不能相互依赖 [operation1 addDependency:operation2]; [operation2 addDependency:operation3]; //创建NSOperationQueue NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:operation1]; [queue addOperation:operation2]; [queue addOperation:operation3];