IOS Multithreading (4) Nsoperation

Source: Internet
Author: User

2.NSOperation
    • 2.1 Nsoperation Basic Use

(1) Related concepts

01 NSOperation是对GCD的包装02 两个核心概念【队列+操作】

(2) Basic use

01 NSOperation本身是抽象类,只能只有它的子类02 三个子类分别是:NSBlockOperation、NSInvocationOperation以及自定义继承自NSOperation的类03 NSOperation和NSOperationQueue结合使用实现多线程并发

(3) Related code

//Nsinvocationoperation    //1. Encapsulation Operations    / * First parameter: target object second parameter: The method to be called by the operation, which accepts a parameter of the third parameter: The parameter passed by the method is called, if the method does not accept the parameter, then the value is nil */Nsinvocationoperation *operation = [[Nsinvocationoperation alloc] Initwithtarget: SelfSelector@selector(Run) object:Nil];//2. Start Operation[Operation start];-------------------------------------------------//Nsblockoperation    //1. Encapsulation Operations    / * Nsblockoperation provides a class method that encapsulates the operation in this class of methods * /Nsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^{//execute in main thread        NSLog(@"---download1--%@",[NsthreadCurrentThread]); }];//2. Append operation, append operation executed in child thread[Operation Addexecutionblock:^{NSLog(@"---download2--%@",[NsthreadCurrentThread]);    }]; [Operation Addexecutionblock:^{NSLog(@"---download3--%@",[NsthreadCurrentThread]); }];//3. Starting the execution action[Operation start];----------------------------------------------//03 Custom Nsoperation    //How to encapsulate the operation?     //Custom nsoperation, by overriding the internal main method for encapsulation operations-(void) Main {NSLog(@"--main--%@",[NsthreadCurrentThread]); }//How to use?     //1. Instantiating a custom Action objectXloperation *op = [[Xloperation alloc]init];//2. Performing Actions[op start];
    • 2.2 Nsoperationqueue Basic use

(1) Two types of queues in nsoperation

01 主队列 通过mainQueue获得,凡是放到主队列中的任务都将在主线程执行02 非主队列 直接alloc init出来的队列。非主队列同时具备了并发和串行的功能,通过设置最大并发数属性来控制任务是并发执行还是串行执行

(2) Related code

//Custom Nsoperation-(void) customoperation{//1. Creating a queueNsoperationqueue *queue = [[Nsoperationqueue alloc]init];//2. Encapsulation Operations    //Benefits: 1. Information concealment    //2. Code ReuseXloperation *OP1 = [[Xloperation alloc]init]; Xloperation *OP2 = [[Xloperation alloc]init];//3. Adding actions to the queue[Queue ADDOPERATION:OP1]; [Queue addoperation:op2];}//nsblockoperation- (void) blockoperation{//1. Creating a queue       / * Concurrency: Global concurrent queue, create yourself (concurrent) Serial: Master queue, create it Yourself (serial) */    //Nsoperationqueue    /* Home column: All tasks placed in the main queue execute [nsoperationqueue Mainqueue] Non-host column: Alloc int with concurrent and serial functions, default is concurrent queue * /Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];//2. Encapsulation OperationsNsblockoperation *OP1 = [Nsblockoperation blockoperationwithblock:^{NSLog(@"1----%@",[NsthreadCurrentThread]);    }]; Nsblockoperation *OP2 = [Nsblockoperation blockoperationwithblock:^{NSLog(@"2----%@",[NsthreadCurrentThread]);    }]; [Op2 addexecutionblock:^{NSLog(@"3----%@",[NsthreadCurrentThread]);    }]; [Op2 addexecutionblock:^{NSLog(@"4----%@",[NsthreadCurrentThread]); }];//3. Adding actions to the queue[Queue ADDOPERATION:OP1];    [Queue ADDOPERATION:OP2]; [Queue ADDOPERATION:OP3];//Supplement: A Simple method[Queue addoperationwithblock:^{NSLog(@"5----%@",[NsthreadCurrentThread]); }];}//nsinvocationoperation- (void) invocation{/ * Queues in GCD: Serial queue: Self-created (serial), Home queue concurrent queues: self-created (concurrent), global concurrent queue nsoperationqueue Home column: [nsoperation Queue Mainqueue]; actions placed in the main queue perform non-home columns in the main thread: [[[Nsoperationqueue Alloc]init], concurrent and serial, default is concurrent execution */    //1. Creating a queueNsoperationqueue *queue = [[Nsoperationqueue alloc]init];//2. Encapsulation OperationsNsinvocationoperation *OP1 = [[Nsinvocationoperation alloc]initwithtarget: SelfSelector@selector(Download1) object:Nil]; Nsinvocationoperation *OP2 = [[Nsinvocationoperation alloc]initwithtarget: SelfSelector@selector(download2) object:Nil]; Nsinvocationoperation *OP3 = [[Nsinvocationoperation alloc]initwithtarget: SelfSelector@selector(DOWNLOAD3) object:Nil];//3. Adding encapsulated operations to the queue[Queue ADDOPERATION:OP1];//[OP1 start][Queue ADDOPERATION:OP2]; [Queue addoperation:op3];}
    • 2.3 Nsoperation Other uses

(1) Set maximum concurrent number "control task concurrency and serial"

//1.创建队列    NSOperationQueue *queue = [[NSOperationQueue alloc]init];    //2.设置最大并发数    //注意点:该属性需要在任务添加到队列中之前进行设置    //该属性控制队列是串行执行还是并发执行    //如果最大并发数等于1,那么该队列是串行的,如果大于1那么是并行的    //系统的最大并发数有个默认的值,为-1,如果该属性设置为0,那么不会执行任何任务    queue2;

(2) Suspension and recovery and cancellation

    //Set pause and resume    //suspended set to Yes to pause, suspended set to No for recovery    //Pause indicates that the next task in the queue is not resumed and the suspend operation can be resumed    if( Self. Queue. issuspended) { Self. Queue. Suspended=NO; }Else{ Self. Queue. Suspended=YES; }//Cancel all operations inside the queue    //Cancel, the next action of the currently executing operation will no longer execute, and will never be executed, as if all subsequent tasks were removed from the queue    //Cancel operation is not recoverable[ Self. QueueCancelalloperations];---------Custom nsoperation cancel Operation---------------------------(void) main{//time-consuming operation 1     for(inti =0; i< +; i++) {NSLog(@"Task 1-%d--%@", i,[NsthreadCurrentThread]); }NSLog(@"+++++++++++++++++++++++++++++++++");//Apple recommends that whenever a time-consuming operation is performed, the current queue is canceled, and if so, exit directly    //benefits can improve the performance of the program    if( Self. iscancelled) {return; }//time-consuming operation 2     for(inti =0; i< +; i++) {NSLog(@"Task 1-%d--%@", i,[NsthreadCurrentThread]); }NSLog(@"+++++++++++++++++++++++++++++++++");}

-2.4 nsoperation operation dependency and monitoring

  //1. Creating a queueNsoperationqueue *queue = [[Nsoperationqueue alloc]init]; Nsoperationqueue *queue1 = [[Nsoperationqueue alloc]init];//2. Encapsulation OperationsNsblockoperation *OP1 = [Nsblockoperation blockoperationwithblock:^{NSLog(@"1----%@",[NsthreadCurrentThread]);    }]; Nsblockoperation *OP2 = [Nsblockoperation blockoperationwithblock:^{NSLog(@"2----%@",[NsthreadCurrentThread]);    }]; Nsblockoperation *OP3 = [Nsblockoperation blockoperationwithblock:^{NSLog(@"3----%@",[NsthreadCurrentThread]);    }]; Nsblockoperation *OP4 = [Nsblockoperation blockoperationwithblock:^{NSLog(@"4----%@",[NsthreadCurrentThread]);    }]; Nsblockoperation *OP5 = [Nsblockoperation blockoperationwithblock:^{ for(NsintegerI=0; i<10000; i++) {NSLog(@"5-%zd---%@", i,[NsthreadCurrentThread]); }    }];//Monitor completeOp4. Completionblock= ^{NSLog(@"OP4 has finished---%@.",[NsthreadCurrentThread]); };//Add operation dependency, note cannot loop dependent[Op1 ADDDEPENDENCY:OP5]; [Op1 ADDDEPENDENCY:OP4];//Add action to queue[Queue ADDOPERATION:OP1];    [Queue ADDOPERATION:OP2];    [Queue ADDOPERATION:OP3];    [Queue ADDOPERATION:OP4]; [Queue1 ADDOPERATION:OP5];

(2) Download multiple picture synthesis case (set operation dependency)

//02 Comprehensive Case- (void) download2{NSLog(@"----");//1. Creating a queueNsoperationqueue *queue = [[Nsoperationqueue alloc]init];//2. Encapsulation operation download Picture 1Nsblockoperation *OP1 = [Nsblockoperation blockoperationwithblock:^{Nsurl*url = [Nsurlurlwithstring:@"Http://h.hiphotos.baidu.com/zhidao/pic/item/6a63f6246b600c3320b14bb3184c510fd8f9a185.jpg"]; NSData *data = [NSData Datawithcontentsofurl:url];//Get Picture data         Self. Image1= [UIImageImagewithdata:data]; }];//3. Encapsulation operation download Picture 2Nsblockoperation *OP2 = [Nsblockoperation blockoperationwithblock:^{Nsurl*url = [Nsurlurlwithstring:@"Http://pic.58pic.com/58pic/13/87/82/27Q58PICYje_1024.jpg"]; NSData *data = [NSData Datawithcontentsofurl:url];//Get Picture data         Self. Image2= [UIImageImagewithdata:data]; }];//4. Compositing picturesNsblockoperation *combine = [Nsblockoperation blockoperationwithblock:^{//4.1 Opening the graphics contextUigraphicsbeginimagecontext (Cgsizemake ( $, $));//4.2 painting Image1[ Self. Image1Drawinrect:cgrectmake (0,0, $, -)];//4.3 painting Image2[ Self. Image2Drawinrect:cgrectmake (0, -, $, -)];//4.4 get the picture data according to the graphic context        UIImage*image = Uigraphicsgetimagefromcurrentimagecontext ();//NSLog (@ "%@", image);        //4.5 Closing the graphics contextUigraphicsendimagecontext ();//7. Back to the main thread refresh UI[[Nsoperationqueue mainqueue]addoperationwithblock:^{ Self. ImageView. Image= Image;NSLog(@"Refresh UI---%@",[NsthreadCurrentThread]);    }]; }];//5. Setting Operation Dependencies[Combine ADDDEPENDENCY:OP1]; [Combine ADDDEPENDENCY:OP2];//6. Adding actions to the queue execution[Queue ADDOPERATION:OP1];    [Queue ADDOPERATION:OP2];    [Queue Addoperation:combine]; }

IOS Multithreading (4) Nsoperation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.