NSOperation是个抽象类,并不具备封装操作的能力,必须使用它的子类
使用NSOperation子类的方式有3种
1、NSInvocationOperation
2、NSBlockOperation
3、自定义子类继承NSOperation,实现内部相应的方法
注意:
默认情况下,NSInvocationOperation调用了start方法后并不会开一条新线程去执行操作,而是在当前线程同步执行操作
只有将NSOperation放到一个NSOperationQueue中,才会异步执行操作
一、队列的取消、暂停、恢复
1.取消队列的所有操作
- (void)cancelAllOperations;
提示:也可以调用NSOperation的- (void)cancel方法取消单个操作2.暂停和恢复队列
- (void)setSuspended:(BOOL)b; // YES代表暂停队列,NO代表恢复队列
- (BOOL)isSuspended;
二、操作优先级
设置NSOperation在queue中的优先级,可以改变操作的执行优先级
- (NSOperationQueuePriority)queuePriority;
- (void)setQueuePriority:(NSOperationQueuePriority)p;
优先级的取值
NSOperationQueuePriorityVeryLow = -8L, NSOperationQueuePriorityLow = -4L, NSOperationQueuePriorityNormal = 0, NSOperationQueuePriorityHigh = 4, NSOperationQueuePriorityVeryHigh = 8
三、操作依赖
NSOperation之间可以设置依赖来保证执行顺序
比如一定要让操作A执行完后,才能执行操作B,可以这么写
[operationB addDependency:operationA]; // 操作B依赖于操作A
可以在不同queue的NSOperation之间创建依赖关系
四、操作的监听
可以监听一个操作的执行完毕
- (void (^)(void))completionBlock; - (void)setCompletionBlock:(void (^)(void))block;
五、实例
1.NSInvocationOperation
//创建后调用start方法会在当前线程中同步执行任务,只有添加到OperationQueue中才有可能异步执行 NSInvocationOperation *opration=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething) object:nil]; [opration start];
执行结果:
2015-09-02 22:18:59.162 OpearationDemo1[1241:99390]
2.放在Queue中
//2.1 封装任务 NSInvocationOperation *opration1=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething) object:nil]; NSInvocationOperation *opration2=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething) object:nil]; NSInvocationOperation *opration3=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething) object:nil]; //2.2 创建队列 NSOperationQueue *queue=[[NSOperationQueue alloc] init]; queue.maxConcurrentOperationCount=2; //设置最大并发数 //设置依赖 [opration1 addDependency:opration2]; //2.3 添加到队列中 [queue addOperation:opration1]; [queue addOperation:opration2]; [queue addOperation:opration3];
执行结果:
{number = 2, name = (null)}
{number = 3, name = (null)}
2015-09-02 22:47:40.214 OpearationDemo1[1431:141437]
3. NSBlockOperation封装任务,
/* NSBlockOperation具备开线程的能力,是否开线程决定于任务的个数 */ NSBlockOperation *opeation=[NSBlockOperation blockOperationWithBlock:^{ NSLog(@"%@ --->执行任务0",[NSThread currentThread]); }]; [opeation addExecutionBlock:^{ NSLog(@"%@ --->执行任务1",[NSThread currentThread]); }]; [opeation addExecutionBlock:^{ NSLog(@"%@ --->执行任务2",[NSThread currentThread]); }]; [opeation start];
运行结果:
{number = 3, name = (null)} —>执行任务0
{number = 2, name = (null)} —>执行任务2
2015-09-02 22:24:35.867 OpearationDemo1[1291:108357]