标签:
一、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,实现内部相应的?法
/*************************************************************/ //即默认情况下,如果操作没有放到队列中queue中,都是同步执行。只有将NSOperation放到一个NSOperationQueue中,才会异步执行操作 NSLog(@"主线程---%@",[NSThread currentThread]); NSInvocationOperation *operation1=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test1) object:nil]; [operation1 start]; /*************************************************************/ //注意:只要NSBlockOperation封装的操作数 > 1,就会异步执行操作 NSBlockOperation *operation2=[NSBlockOperation blockOperationWithBlock:^{ for (int i=1; i<5; i++) { NSLog(@"NSBlockOperation1----%@",[NSThread currentThread]);} }]; [operation2 addExecutionBlock:^{ for (int i=1; i<5; i++) { NSLog(@"NSBlockOperation2----%@",[NSThread currentThread]);} }]; [operation2 addExecutionBlock:^{ for (int i=1; i<5; i++) { NSLog(@"NSBlockOperation3----%@",[NSThread currentThread]); } }]; //放入队列后就不需要这句; [operation2 start]; /*************************************************************/ /*1)先将需要执行的操作封装到一个NSOperation对象中 (2)然后将NSOperation对象添加到NSOperationQueue中 (3)系统会?动将NSOperationQueue中的NSOperation取出来 (4)将取出的NSOperation封装的操作放到?条新线程中执? */ NSInvocationOperation *operation3=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test3) object:nil]; NSInvocationOperation *operation4=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test4) object:nil]; NSOperationQueue *queue=[[NSOperationQueue alloc]init]; [queue addOperation:operation2]; [queue addOperation:operation3]; [queue addOperation:operation4];
/*************************************************************/ -(void)test1{ NSLog(@"operation1--test1---%@",[NSThread currentThread]); } -(void)test3{ for (int i=1; i<5; i++) { NSLog(@"NSOperationQueue-test3----%@",[NSThread currentThread]); } } -(void)test4{ for (int i=1; i<5; i++) { NSLog(@"NSOperationQueue--test4---%@",[NSThread currentThread]); } }
标签:
原文地址:http://www.cnblogs.com/sunjianfei/p/5725135.html