iOS Multithreading implementation 4-nsoperation

Source: Internet
Author: User

First, Introduction

Nsoperation is an abstract class, we can use a system-provided subclass or implement its own subclass, with the following features:

A. is an object-oriented package based on GCD in the OC language;

B. Easier to use than gcd (object oriented);

C. Provides some features that are not implemented with GCD (http://www.cnblogs.com/mddblog/p/4767559.html), such as tasks that can be canceled in the task processing queue, add dependencies between tasks, and so on;

D. Apple recommends using nsoperation without caring about thread and thread life cycle;

E. You can specify a dependency between actions, which is to add the action to the queue.

F. Concurrent queues, asynchronous execution (multiple threads, unordered execution).

Nsoperation convenient unified management, suitable for some large-scale complex occasions, such as our commonly used network framework: afnetworking, Sdwebimage and so on.

Second, Nsoperation sub-class

Nsoperation is an abstract class that implements the Nsoperation subclass in 3 ways:

1) Nsinvocationoperation: less use;

2) Nsblockoperation: often used;

3) Customize the subclass inheritance Nsoperation, implement the internal corresponding method: seldom used.

All we have to do is add any one of the above 3 operations to Nsoperationqueue to use.

  1 nsinvocationoperation

  1) perform operation directly (synchronous)

1 ///Click on the screen call to create an action and execute2- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event {3Nsinvocationoperation *operation = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (Demo:)Object:@"This is a parameter"];4 [Operation start];5 }6 ///prints the parameter to the current thread7- (void) Demo: (NSString *) str {8NSLog (@"%@--%@", Str,[nsthread CurrentThread]);9 }Ten  One Printing results: A  -- the- -  the: One:54.030nsoperationtest[2595:162235] This is a parameter <nsthread:0x7fa759c173a0>{number =1, name = main}

The 3rd line of code creation initializes a Nsinvocationoperation object and creates an action based on an object (self) and selector, and the 4th line executes the action demo: and passes a parameter. By default, when the Start method is called, it does not open a new thread to perform the operation, but instead performs the operation synchronously on the current thread. An operation is performed asynchronously only if the operation is placed in a nsoperationqueue.

2) Add operation to Nsoperationqueue execution

1 ///Click on the screen call to create an action and execute2- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event {3 [self invocationtest];4 }5 ///add an action to a queue6- (void) Invocationtest {7     //Create an action queue8Nsoperationqueue *operationqueue =[[Nsoperationqueue alloc] init];9     //Create action (the last object argument is the parameter passed to the selector method)TenNsinvocationoperation *operation = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (Demo:)Object:@"This is a parameter"]; One     //to add an action to an action queue A [Operationqueue addoperation:operation]; - } - ///prints the parameter to the current thread the- (void) Demo: (NSString *) str { -NSLog (@"%@--%@", Str,[nsthread CurrentThread]); - } -  + /*Print Results*/ -  -- the- -  the: $:23.777nsoperationtest[2943:182362] This is a parameter--<nsthread:0x7ff68af15b00>{number =2, name = (NULL)}

Based on the printed results, it can be seen that a new thread has been opened and executed asynchronously.

  2 nsblockoperation

  1) Perform an operation (synchronous)

Nsblockoperation *operation = [nsblockoperation blockoperationwithblock:^() {    NSLog (@ "%@  ", [Nsthread CurrentThread]);}]; // start to perform a task [operation start]; execution Result: ----£ º58.791 nsoperationtest[  3015:1913170x7fe6abd02b701, name = main}

You can see that this method is very simple and somewhat similar to GCD, which is also performed synchronously.

2) Add multiple operations Execution (async)

//Initialize an objectNsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^() {NSLog (@"1:%@", [Nsthread CurrentThread]);}];//Add 3 more Actions[Operation addexecutionblock:^() {NSLog (@"2:%@", [Nsthread CurrentThread]);}]; [Operation Addexecutionblock:^() {NSLog (@"3:%@", [Nsthread CurrentThread]);}]; [Operation Addexecutionblock:^() {NSLog (@"4:%@", [Nsthread CurrentThread]);}];//start to perform a task[operation start]; execution Result: -- the- -  the: -:48.372nsoperationtest[3113:198447]1: <nsthread:0x7f9282f04e10>{number =1, name =Main} -- the- -  the: -:48.372nsoperationtest[3113:198530]2: <nsthread:0x7f9282e081c0>{number =2, name = (NULL)} -- the- -  the: -:48.372nsoperationtest[3113:198532]4: <nsthread:0x7f9282c1a380>{number =4, name = (NULL)} -- the- -  the: -:48.372nsoperationtest[3113:198533]3: <nsthread:0X7F9282E0EC90>{number =3, name = (NULL)}

When multiple operations are added, a new thread is opened to execute asynchronously.

3 Custom Nsoperation

  Custom The main thing about Nsoperation is the overloaded-(void) Main method, in which you add the actions that need to be performed. When this is done, the system automatically calls the-(void) Main method.

#import " CustomOpertaionTest.h " @implementation customopertaiontest-(void) main {    //  Create a new auto-free pool to avoid memory leaks     @autoreleasepool {        //  executed code        NSLog (@ " This is a test:%@ " , [Nsthread CurrentThread]);}    } @end

Called in the host controller, altogether two kinds: one synchronous asynchronous

/********************1. Direct execution, synchronous ***************/customopertaiontest*operation =[[Customopertaiontest alloc] init];//start to perform a task[operation start]; execution Result: -- the- -  -: -:27.620nsoperationtest[3368:222036] This is a test: <nsthread:0x7ff420d28000>{number =1, name =Main}/********************2. Adding to queues, asynchronous ***************/Nsoperationqueue*operationqueue =[[Nsoperationqueue alloc] init]; Customopertaiontest*operation =[[Customopertaiontest alloc] init]; [Operationqueue addoperation:operation]; Execution results: -- the- -  -: -:13.594nsoperationtest[3401:225178] This is a test: <nsthread:0X7FF2D0539D70>{number =2, name = (NULL)}

Third, other common methods

 1) Cancel the operation, operation start execution, the default will continue to perform the operation until completion, we can also call the Cancel method to cancel the operation

[Operation Cancel];

Here is a question, our custom operation, if the support is canceled, you should be in the overloaded main function to query whether the user canceled the operation, especially when the main function in the loop must be queried. Then release the resource and exit the main function.

2) If you want to do something after a nsoperation has finished executing

Operation.completionblock = ^() {    //  All operations executed after completion };

3) Set the maximum number of concurrent, by default the maximum number of concurrent is 6, that is, at the same time, only 6 threads are allowed to be in a ready state.

// Maximum number of concurrent 3 [Operationqueue setmaxconcurrentoperationcount:3];

4) Can you set dependencies to guarantee the order of execution? If you have to make operation a complete, you can perform operation B, as follows:

But be careful not to rely on B for a, and then B to rely on a, so that A and B interdependence can not be implemented. If A and B are in different operations queues, you can also set dependencies.

iOS Multithreading implementation 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.