一、NSOperation简介
1.简单说明
NSOperation的作⽤:配合使用NSOperation和NSOperationQueue也能实现多线程编程
NSOperation和NSOperationQueue实现多线程的具体步骤:
(1)先将需要执行的操作封装到一个NSOperation对象中
(2)然后将NSOperation对象添加到NSOperationQueue中
(3)系统会⾃动将NSOperationQueue中的NSOperation取出来
(4)将取出的NSOperation封装的操作放到⼀条新线程中执⾏
2.NSOperation的子类
NSOperation是个抽象类,并不具备封装操作的能力,必须使⽤它的子类
使用NSOperation⼦类的方式有3种:
(1)NSInvocationOperation
(2)NSBlockOperation
(3)自定义子类继承NSOperation,实现内部相应的⽅法
二、 具体说明
1.NSInvocationOperation子类
- (void)viewDidLoad
{
[super viewDidLoad];
//NSOperation:抽象类,不具备封装功能
//创建操作对象,封装要执行的任务
//NSInvocationOperation 封装操作
NSInvocationOperation *operation=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
//执行操作
[operation start];
}
-(void)test{
NSLog(@"--test--%@--",[NSThread currentThread]);
}
2.NSBlockOperation子类
- (void)viewDidLoad {
[super viewDidLoad];
//创建NSBlockOperation操作对象 //创建NSBlockOperation操作对象
NSBlockOperation *operation=[NSBlockOperation blockOperationWithBlock:^{
NSLog(@"NSBlockOperation------%@",[NSThread currentThread]);
}];
//添加操作
[operation addExecutionBlock:^{
NSLog(@"NSBlockOperation1------%@",[NSThread currentThread]);
}];
[operation addExecutionBlock:^{
NSLog(@"NSBlockOperation2------%@",[NSThread currentThread]);
}];
//开启执行操作
[operation start];
}
3.NSOperationQueue
- (void)viewDidLoad{
[super viewDidLoad];
//创建NSInvocationOperation对象,封装操作
NSInvocationOperation *operation1=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test1) object:nil];
NSInvocationOperation *operation2=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test2) object:nil];
//创建对象,封装操作
NSBlockOperation *operation3=[NSBlockOperation blockOperationWithBlock:^{
NSLog(@"NSBlockOperation3--1----%@",[NSThread currentThread]);
}];
[operation3 addExecutionBlock:^{
NSLog(@"NSBlockOperation3--2----%@",[NSThread currentThread]);
}];
//创建NSOperationQueue
NSOperationQueue * queue=[[NSOperationQueue alloc]init];
//把操作添加到队列中
[queue addOperation:operation1];
[queue addOperation:operation2];
[queue addOperation:operation3];
}
-(void)test1
{
NSLog(@"NSInvocationOperation--test1--%@",[NSThread currentThread]);
}
-(void)test2
{
NSLog(@"NSInvocationOperation--test2--%@",[NSThread currentThread]);
}