iOS multithreaded Development nsoperation-get in the car, there's no time to explain!

Source: Internet
Author: User

First, what is Nsoperation?

Nsoperation is a multi-threaded solution offered by Apple. In fact, Nsoperation is based on the GCD higher layer of encapsulation, but more object-oriented than GCD, code readability, more controllable, very cock is added to the operation of dependency.

By default, Nsoperation can only perform operations synchronously when used alone, and does not have the ability to open new threads, only with Nsoperationqueue for asynchronous execution. Here, we are not difficult to find GCD and nsoperation implementation of the way very much like, in fact, this is more like nonsense, nsoperation itself is based on GCD packaging, nsoperation equivalent to GCD in the task, And Nsoperationqueue is equivalent to GCD in the queue, in front of the "iOS multithreaded Development gcd (previous)" has elaborated the essence of GCD: Developers have to do is to define the task to be performed and append to the appropriate dispatch queue. We can also say that the essence of nsoperation is to define the task (Nsoperation) to be performed and append it to the appropriate nsoperationqueue.

Second, the use of nsoperation

1. Create a task

Nsoperation is an abstract base class that represents an independent unit of computation that can provide useful and thread-safe establishment states, priorities, dependencies, and cancellations for subclasses. But it can not be used directly to encapsulate the task, only through its subclasses to encapsulate, general we may use: nsblockoperation, nsinvocationoperation, or define a subclass that inherits from Nsoperation, Encapsulates a task by implementing an internal appropriate method.

(1) nsblockoperation

-(void) invocationoperation{    NSLog (@ "Start-%@", [Nsthread CurrentThread]);        Create Nsinvocationoperation object    nsinvocationoperation *op = [[Nsinvocationoperation alloc] Initwithtarget:self Selector: @selector (TestRun) Object:nil];        Call the Start method to start the Operation    [op start];        NSLog (@ "End-%@", [Nsthread CurrentThread]);} -(void) testrun{    NSLog (@ "invocationoperation-%@", [Nsthread CurrentThread]);}

Execution Result:

2017-07-14 13:43:59.327 beck.wang[10248:1471363] Start-<nsthread:0x6100000614c0>{number = 1, name = main}2017-07 -14 13:43:59.328 beck.wang[10248:1471363] invocationoperation--<nsthread:0x6100000614c0>{number = 1, name = Main }2017-07-14 13:43:59.328 beck.wang[10248:1471363] End-<nsthread:0x6100000614c0>{number = 1, name = main}

Analysis: In the case of Nsinvocationoperation alone, Nsinvocationoperation performs the operation on the main thread synchronously and does not open a new thread.

(2) Nsblockoperation

-(void) blockoperation{        NSLog (@ "Start-%@", [Nsthread CurrentThread]);    Nsblockoperation *op = [nsblockoperation blockoperationwithblock:^{                NSLog (@ "blockoperation--%@", [NSThread CurrentThread]);    }];        NSLog (@ "End-%@", [Nsthread CurrentThread]);        [op start];}

Printing results:

2017-07-14 13:49:25.436 beck.wang[10304:1476355] Start-<nsthread:0x6100000653c0>{number = 1, name = main}2017-07 -14 13:49:25.436 beck.wang[10304:1476355] End-<nsthread:0x6100000653c0>{number = 1, name = main}2017-07-14 13:49: 25.436 beck.wang[10304:1476355] Blockoperation--<nsthread:0x6100000653c0>{number = 1, name = main}

Analysis: In the case of using nsblockoperation alone, Nsblockoperation is also performing operations on the main thread without opening a new thread.

It is important to note that Nsblockoperation also provides a method addExecutionBlock: by which additional addExecutionBlock: operations can be added to the nsblockoperation, which are executed concurrently on other threads.

-(void) blockoperation{        NSLog (@ "Start-%@", [Nsthread CurrentThread]);    Nsblockoperation *op = [nsblockoperation blockoperationwithblock:^{                NSLog (@ "blockoperation--%@", [NSThread CurrentThread]);    }];        Add additional tasks (performed on child threads)    [op addexecutionblock:^{        NSLog (@ "AddTask1---%@", [Nsthread CurrentThread]);    }];    [Op addexecutionblock:^{        NSLog (@ "AddTask2---%@", [Nsthread CurrentThread]);    }];    [Op addexecutionblock:^{        NSLog (@ "AddTask3---%@", [Nsthread CurrentThread]);    }];        NSLog (@ "End-%@", [Nsthread CurrentThread]);        [op start];}

Printing results:

2017-07-14 13:57:02.009 beck.wang[10351:1482603] Start-<nsthread:0x60000007cdc0>{number = 1, name = main}2017-07 -14 13:57:02.009 beck.wang[10351:1482603] End-<nsthread:0x60000007cdc0>{number = 1, name = main}2017-07-14 13:57: 02.010 beck.wang[10351:1482603] Blockoperation--<nsthread:0x60000007cdc0>{number = 1, name = main}2017-07-14 13:57:02.010 beck.wang[10351:1482642] AddTask1---<nsthread:0x618000260e00>{number = 3, name = (NULL)}2017-07-14 13:57:02.010 beck.wang[10351:1482645] ADDTASK3---<nsthread:0x600000263200>{number = 5, name = (NULL)}2017-07-14 13:57:02.010 beck.wang[10351:1482643] addTask2---<nsthread:0x610000264600>{number = 4, name = (NULL)}

Analysis: The Blockoperationwithblock task executes in the main thread, and the Addexecutionblock task executes in the new thread.

(3) Custom nsoperation subclass--Rewrite the main method to

. h

@interface Ztoperation:nsoperation@end

. m

@implementation ztoperation-(void) main{    //Here you can customize the task    NSLog (@ "ztoperation--%@", [Nsthread CurrentThread]);} @end

Viewcontroller

Ztoperation *zt = [[Ztoperation alloc] init]; [ZT start];

Printing results:

2017-07-14 14:05:58.824 beck.wang[10389:1490955] ztoperation--<nsthread:0x60000007a940>{number = 1, name = main}

Analysis: The task executes in the main thread and does not open new threads.

2. Create a queue

NSOperationQueuethere are altogether two kinds of queues: The primary queue, the other queue. The other queues include serial, concurrency, serial, concurrency by setting the maximum number of concurrent Maxconcurrentoperationcount!

(1) Home Row--the task executes in the main thread

Nsoperationqueue *mainqueue = [Nsoperationqueue mainqueue];

(2) Other queues--tasks are performed in child threads

Nsoperationqueue *elsequeue = [[Nsoperationqueue alloc] init];

3, Nsoperation + nsoperationqueue (task append to queue)

Add a single action:-(void) Addoperation: (Nsoperation *) op;//Add multiple actions:-(void) Addoperations: (nsarray<nsoperation *> *) Ops Waituntilfinished: (BOOL) Wait ns_available (10_6, 4_0);//Add block operation:-(void) Addoperationwithblock: (void (^) (void)) Block Ns_available (10_6, 4_0);

code example:

-(void) addoperationtoqueue{        NSLog (@ "Start-%@", [Nsthread CurrentThread]);        Create Queue    Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];        Create Nsinvocationoperation    nsinvocationoperation *op1 = [[Nsinvocationoperation alloc] Initwithtarget:self Selector: @selector (TestRun) Object:nil];        Create Nsblockoperation    nsblockoperation *op2 = [nsblockoperation blockoperationwithblock:^{        NSLog (@ "task002- -%@ ", [Nsthread CurrentThread]);    }];        Add action to queue: addoperation:    [queue addoperation:op1];    [Queue addoperation:op2];        Add action to queue: Addoperationwithblock:    [Queue addoperationwithblock:^{        NSLog (@ "task003-----%@", [Nsthread CurrentThread]);    }];        NSLog (@ "End-%@", [Nsthread CurrentThread]);} -(void) testrun{    NSLog (@ "task001-%@", [Nsthread CurrentThread]);}

Printing results:

2017-07-14 14:39:51.669 beck.wang[10536:1516641] Start-<nsthread:0x610000077640>{number = 1, name = main}2017-07 -14 14:39:51.670 beck.wang[10536:1516641] End-<nsthread:0x610000077640>{number = 1, name = main}2017-07-14 14:39: 51.670 beck.wang[10536:1516686] task003-----<nsthread:0x600000077200>{number = 3, name = (NULL)}2017-07-14 14:39:51.670 beck.wang[10536:1516689] task002--<nsthread:0x61800007e080>{number = 5, name = (null)}2017-07-14 14 : 39:51.670 beck.wang[10536:1516687] task001--<nsthread:0x61000007e1c0>{number = 4, name = (NULL)}

Analysis: Opens a new thread and executes concurrently.

Third, Nsoperationqueue management

1, the queue cancellation, pause, restore

-(void) cancel; Nsoperation provides a way to cancel a single operation

-(void) cancelalloperations; Nsoperationqueue provides methods that can cancel all operations of a queue

-(void) setsuspended: (BOOL) b; can set pause and resume of task, yes means pause queue, no represents recovery queue

-(BOOL) issuspended; To determine the paused state

Pausing or canceling does not immediately pause or cancel the operation that is being performed, but does not perform a new operation after the current operation has finished executing. The difference between the two is that after pausing the operation, you can resume the operation and continue down, and after canceling the operation, all the operations are emptied and no further action is taken.

2, maximum concurrent number Maxconcurrentoperationcount

Maxconcurrentoperationcount = 1 means unrestricted, default concurrency execution;

Maxconcurrentoperationcount = 1 indicates a maximum concurrent number of 1, serial execution;

Maxconcurrentoperationcount > ([Count] > =1) indicates concurrent execution, Min[count, system restrictions].

code example:

-(void) operationqueue{    nsoperationqueue *queue = [[Nsoperationqueue alloc] init];        Set maximum number of concurrent operations    //Queue.maxconcurrentoperationcount =-1;  Concurrent execution    //Queue.maxconcurrentoperationcount = 1;//synchronous execution     Queue.maxconcurrentoperationcount = 2;//concurrent Execution        [ Queue addoperationwithblock:^{        NSLog (@ "Task1-----%@", [Nsthread CurrentThread]);    }];    [Queue addoperationwithblock:^{        NSLog (@ "task2-----%@", [Nsthread CurrentThread]);    }];    [Queue addoperationwithblock:^{        NSLog (@ "TASK3-----%@", [Nsthread CurrentThread]);    }];    [Queue addoperationwithblock:^{        NSLog (@ "TASK4-----%@", [Nsthread CurrentThread]);    }];    [Queue addoperationwithblock:^{        NSLog (@ "task5-----%@", [Nsthread CurrentThread]);    }];    [Queue addoperationwithblock:^{        NSLog (@ "task6-----%@", [Nsthread CurrentThread]);}    ];}

Printing results:

Queue.maxconcurrentoperationcount =-12017-07-14 15:28:39.554 beck.wang[10772:1557342] task2-----<NSThread: 0x61800006d340>{number = 4, name = (null)}2017-07-14 15:28:39.554 beck.wang[10772:1557358] TASK3-----<nsthread: 0x6080000751c0>{number = 5, name = (null)}2017-07-14 15:28:39.554 beck.wang[10772:1557359] TASK4-----<nsthread: 0x610000071c00>{number = 6, name = (null)}2017-07-14 15:28:39.554 beck.wang[10772:1557339] TASK5-----<nsthread: 0x60000006ea40>{number = 7, name = (null)}2017-07-14 15:28:39.554 beck.wang[10772:1557340] Task1-----<nsthread: 0x608000073500>{number = 3, name = (null)}2017-07-14 15:28:39.554 beck.wang[10772:1557360] TASK6-----<nsthread: 0x610000071c80>{number = 8, name = (NULL)}//analysis: The number of threads is 6, Concurrent execution-----------------------------------Split line----------------------------------------------// Queue.maxconcurrentoperationcount = 12017-07-14 15:27:04.365 beck.wang[10743:1555231] Task1-----<NSThread: 0x60800007c880>{number = 3, name= (null)}2017-07-14 15:27:04.365 beck.wang[10743:1555231] task2-----<nsthread:0x60800007c880>{number = 3, name = (NULL)} 2017-07-14 15:27:04.365 beck.wang[10743:1555231] task3-----<nsthread:0x60800007c880>{number = 3, name = (NULL)} 2017-07-14 15:27:04.365 beck.wang[10743:1555231] task4-----<nsthread:0x60800007c880>{number = 3, name = (NULL)} 2017-07-14 15:27:04.366 beck.wang[10743:1555231] task5-----<nsthread:0x60800007c880>{number = 3, name = (NULL)} 2017-07-14 15:27:04.366 beck.wang[10743:1555231] task6-----<nsthread:0x60800007c880>{number = 3, name = (NULL)}/ /analysis: Number of threads is 1, synchronous execution-----------------------------------Split line----------------------------------------------// Queue.maxconcurrentoperationcount = 22017-07-14 15:18:26.162 beck.wang[10715:1548342] task2-----<NSThread: 0x608000079740>{number = 4, name = (null)}2017-07-14 15:18:26.162 beck.wang[10715:1548344] Task1-----<nsthread: 0x6100000770c0>{number = 3, name = (null)}2017-07-14 15:18:26.162 BECK.WANG[10715:1548342] TASK4-----<nsthread:0x608000079740>{number = 4, name = (null)}2017-07-14 15:18:26.162 BECK.WANG[10715:1548344] TASK3-----<nsthread:0x6100000770c0>{number = 3, name = (null)}2017-07-14 15:18:26.162 BECK.WANG[10715:1548342] task5-----<nsthread:0x608000079740>{number = 4, name = (null)}2017-07-14 15:18:26.163 BECK.WANG[10715:1548344] TASK6-----<nsthread:0x6100000770c0>{number = 3, name = (NULL)}//Analysis: Number of threads 2, concurrent execution

Obviously, it is much easier to implement concurrent and serial functions by setting maxconcurrentoperationcount than GCD!

3. Operation Dependent

In Nsoperation we can break down the operations into several small tasks and manipulate them by adding dependencies between them, which is often used! This is also nsoperation attractive place, do not need to use complex code implementation like GCD, adddependency can be done!

-(void) adddependency{    nsoperationqueue *queue = [[Nsoperationqueue alloc] init];        Nsblockoperation *OP1 = [nsblockoperation blockoperationwithblock:^{        Sleep (2);        NSLog (@ "Task1-----%@", [Nsthread  CurrentThread]);    }];    Nsblockoperation *OP2 = [nsblockoperation blockoperationwithblock:^{        NSLog (@ "task2-----%@", [Nsthread  CurrentThread]);    }];    Nsblockoperation *OP3 = [nsblockoperation blockoperationwithblock:^{        NSLog (@ "TASK3-----%@", [Nsthread  CurrentThread]);    }];        OP2 depends on OP1 execution order OP1->OP2 must be placed before [Add operation queue]    [OP2 ADDDEPENDENCY:OP1];        Bogey cycle relies on OP2 has been dependent on OP1, must not let OP1 rely on OP2, the formation of cyclic dependence    //[op1 adddependency:op2];        Add Operation queue    [queue Addoperation:op1];    [Queue addoperation:op2];    [Queue addoperation:op3];}
Printing results:
2017-07-14 15:46:02.011 beck.wang[10854:1571574] task3-----<nsthread:0x61800006d740>{number = 3, name = (NULL)} 2017-07-14 15:46:04.085 beck.wang[10854:1571596] task1-----<nsthread:0x60000006f040>{number = 4, name = (NULL)} 2017-07-14 15:46:04.085 beck.wang[10854:1571574] task2-----<nsthread:0x61800006d740>{number = 3, name = (NULL)}

Analysis: Task2 must be executed behind TASK1 because the thread is set to wait 2s before executing task1, and all task3 are executed at the earliest.

4. Operation Priority

Nsoperationqueuepriorityverylow = -8l,nsoperationqueueprioritylow = -4l,nsoperationqueueprioritynormal = 0, Nsoperationqueuepriorityhigh = 4,nsoperationqueuepriorityveryhigh = 8

5, the operation of monitoring

Can listen to an operation is completed, such as downloading pictures, you need to download the first image before downloading the second picture, here you can set up monitoring.

-(void) addlisting{    nsoperationqueue *queue=[[nsoperationqueue alloc]init];        Nsblockoperation *operation=[nsblockoperation blockoperationwithblock:^{for        (int i=0; i<3; i++) {            NSLog (@ "Download Picture 1-%@", [Nsthread CurrentThread]);        }    ];        Listen operation completed    operation.completionblock=^{        //Continue to download picture operation        NSLog (@ "-Download picture 2--");    };       [Queue addoperation:operation];}

Execution Result:

2017-07-14 16:21:43.833 beck.wang[10930:1597954] Download Picture 1-<nsthread:0x61800007a340>{number = 3, name = (NULL)} 2017-07-14 16:21:43.834 beck.wang[10930:1597954] Download Picture 1-<nsthread:0x61800007a340>{number = 3, name = (NULL)} 2017-07-14 16:21:43.834 beck.wang[10930:1597954] Download Picture 1-<nsthread:0x61800007a340>{number = 3, name = (NULL)} 2017-07-14 16:21:43.834 beck.wang[10930:1597955]--Download Image 2--

Analysis: Download image 1 is completed before the download Image 2, which is similar to the addition of Knowledge point 3 dependency.

Stay in the last words: multithreading is not just a gcd! If you haven't used nsoperation yet, what are you talking about? Get the drill! Of course they each have the use of the scene, the existence is reasonable! iOS multi-Threading three kinds of technology GCD, Nsthread, nsoperation are all finished, need to know GCD, Nsthread can look back to my previous blog.

iOS multithreaded Development nsoperation-get in the car, there's no time to explain!

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.