-
NSOperation几个词搞清就算是了解了"基本"
- 1.操作,两种创建操作的方法
- 2.队列.把操作放到队列执行任务.
- 3.操作之间关系设置(操作依赖)
- 4.NSOperationQueue的特点:暂停.取消,继续
看测试代码如下:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建队列
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
//创建操作方式一
NSInvocationOperation * op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(testOp1) object:nil];
//创建操作方式二
NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Op2 -----%@",[NSThread currentThread]);
}];
//以下几个操作是为了方便演示
NSBlockOperation * op7 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Op7 -----%@",[NSThread currentThread]);
}];
NSBlockOperation * op5 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Op5 -----%@",[NSThread currentThread]);
}];
NSBlockOperation * op6 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Op6 -----%@",[NSThread currentThread]);
}];
NSInvocationOperation * op3 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(testOp3) object:nil];
NSInvocationOperation * op4 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(testOp4) object:nil];
NSLog(@"mainQueue - %@",[NSThread currentThread]);
/**
1.最大并发数是10,但是同时执行的操作的线程只有5个例如线程number 2~6.则:
2.其余两个任务(op)执行时所在的线程可能在上面的线程,也可能不在上面的线程.
*/
//设置最大并发数
queue.maxConcurrentOperationCount = 10;
//将操作op添加到创建的队列queue,还有一个方法是直接添加操作数组也可以
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:op3];
/**
1.线程依赖
2.op1总是在op2前面执行
3.要避免循环依赖
*/
[op1 addDependency:op2];
[queue addOperation:op4];
[queue addOperation:op5];
[queue addOperation:op6];
[queue addOperation:op7];
}
- 看图
- 一下是测试op操作的方法.
-(void)testOp4{
NSLog(@"op4---%@",[NSThread currentThread]);
}
-(void)testOp3{
NSLog(@"op3---%@",[NSThread currentThread]);
}
-(void)testOp1{
NSLog(@"op1------%@",[NSThread currentThread]);
}
@end