1.就基本使用
NSInvocationOperation
//1.创建操作对象,封装需要执行的任务 NSInvocationOperation * operation =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil]; //2.执行操作(默认情况下,如果操作没有放到队列queue中,都是同步执行) [operation start]; - (void)download{ NSLog(@"--------下载图片-----%@",[NSThread currentThread]); }
NSBlockOperation
//1.封装操作 NSBlockOperation * operation=[NSBlockOperation blockOperationWithBlock:^{ NSLog(@"--------下载图片-----%@",[NSThread currentThread]); }]; [operation addExecutionBlock:^{ NSLog(@"--------下载图片1-----%@",[NSThread currentThread]); }]; [operation addExecutionBlock:^{ NSLog(@"--------下载图片2-----%@",[NSThread currentThread]); }]; //2.执行操作 [operation start]; //注意:只要NSBlockOperation封装的操作数>1,就会异步执行操作
NSOperationQueue 操作队列
//创建操作队列 NSOperationQueue * queue =[[NSOperationQueue alloc]init]; NSInvocationOperation *operation1 =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil]; NSInvocationOperation * operation2 =[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(run) object:nil]; NSBlockOperation * operation3 =[NSBlockOperation blockOperationWithBlock:^{ NSLog(@"--------下载图片2-----%@",[NSThread currentThread]); }]; [operation3 addExecutionBlock:^{ NSLog(@"--------run2-----%@",[NSThread currentThread]); }]; [queue addOperation:operation1]; [queue addOperation:operation2]; [queue addOperation:operation3]; //将操作放在队列里才能异步操作
*设置最大并发数
- (void)setMaxConcurrentOperationCount:(NSInteger )cnt;
*设置依赖
[opetationB addDependency:operationA];//操作B依赖于操作A A执行完才会执行B