IOS multithreading implementation 4-NSOperation, ios4-nsoperation

Source: Internet
Author: User

IOS multithreading implementation 4-NSOperation, ios4-nsoperation

I. Introduction

NSOperation is an abstract class. We can use the subclass provided by the system or implement its own subclass. It has the following features:

A. GCD-Based Object-Oriented encapsulation in OC language;

B. It is easier to use than GCD (Object-Oriented );

C. provides some functions that are not implemented well with GCD (http://www.cnblogs.com/mddblog/p/4767559.html), such as canceling tasks in the task processing queue, adding dependencies between tasks and so on;

D. It is recommended for use by Apple. NSOperation does not need to care about the thread and thread lifecycle;

E. You can specify the dependency between operations to add operations to the queue.

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

NSOperation facilitates unified management and is suitable for large and complex scenarios, such as our common network frameworks AFNetworking and SDWebImage.

Ii. NSOperation subclass

NSOperation is an abstract class. There are three ways to implement NSOperation subclass:

1) NSInvocationOperation: rarely used;

2) NSBlockOperation: Frequently used;

3) The Custom subclass inherits NSOperation and implements the corresponding internal method: rarely used.

All we need to do is add any of the above three operations to NSOperationQueue for use.

  1 NSInvocationOperation

  1) perform operations directly (synchronize)

1 // click the screen call to create an operation and execute 2-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {3 NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (demo :) object: @ "this is a parameter"]; 4 [operation start]; 5} 6 // print the parameter and the current thread 7-(void) demo :( NSString *) str {8 NSLog (@ "% @ -- % @", str, [NSThread currentThread]); 9} 10 11 print result: 12 15:11:54. 030 NSOperationTest [2595: 162235] This is a parameter <NSThread: 0x7fa759c173a0 >{number = 1, name = main}

The first line of code creates and initializes an NSInvocationOperation object, and creates an operation based on an object (self) and selector. The second line of code executes the operation demo and passes a parameter. By default, after the start method is called, a new thread is not opened to execute the operation, but the operation is executed synchronously in the current thread. The operation is performed asynchronously only when operation is put into a NSOperationQueue.

2) Add the operation to NSOperationQueue for execution

1 // click the screen call to create an operation and execute 2-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {3 [self invocationTest]; 4} 5 // Add the operation to queue 6-(void) invocationTest {7 // create operation queue 8 NSOperationQueue * operationQueue = [[NSOperationQueue alloc] init]; 9 // create an operation (the final object parameter is the parameter passed to the selector method) 10 NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (demo :) object: @ "this is a parameter"]; 11 // Add the operation to the operation queue 12 [operationQueue addOperation: operation]; 13} 14 // print the parameter and the current thread 15-(void) demo :( NSString *) str {16 NSLog (@ "% @ -- % @", str, [NSThread currentThread]); 17} 18 19/* print the result */20 15:36:23. 777 NSOperationTest [2943: 182362] This is a parameter -- <NSThread: 0x7ff68af15b00> {number = 2, name = (null )}

According to the print results, we can see that a new thread is enabled to execute operations asynchronously.

  2 NSBlockOperation

  1) execute an operation (synchronization)

NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ () {NSLog (@ "% @", [NSThread currentThread]);}]; // starts executing the task [operation start]; execution result: 15:47:58. 791 NSOperationTest [3015: 191317] <NSThread: 0x7fe6abd02b70> {number = 1, name = main}

It can be seen that this method is very simple, a bit similar to GCD, it is also executed synchronously.

2) add multiple operations for execution (asynchronous)

// Initialize an object NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ () {NSLog (@ "1: % @", [NSThread currentThread]);}]; // Add 3 more operations [operation addExecutionBlock: ^ () {NSLog (@ "2: % @", [NSThread currentThread]) ;}]; [operation addExecutionBlock: ^ () {NSLog (@ "3: % @", [NSThread currentThread]) ;}]; [operation addExecutionBlock: ^ () {NSLog (@ "4: % @", [NSThread currentThread]) ;}]; // start the execution task [operation start]; execution result: 15:55:48. 372 NSOperationTest [3113: 198447] 1: <NSThread: 0x7f9282f04e10> {number = 1, name = main} 15:55:48. 372 NSOperationTest [3113: 198530] 2: <NSThread: 0x7f9282e081c0> {number = 2, name = (null)} 15:55:48. 372 NSOperationTest [3113: 198532] 4: <NSThread: 0x7f9282c1a380> {number = 4, name = (null)} 15:55:48. 372 NSOperationTest [3113: 198533] 3: <NSThread: 0x7f9282e0ec90> {number = 3, name = (null )}

When multiple operations are added, a new thread is enabled for asynchronous execution.

3. Custom NSOperation

  The most important part of custom NSOperation is to reload the (void) main method and add the operation to be executed in this method. When this operation is performed, the system automatically calls the-(void) main method.

# Import "CustomOpertaionTest. h "@ implementation CustomOpertaionTest-(void) main {// create an automatic release pool to avoid Memory leakage @ autoreleasepool {// run the code NSLog (@" this is a test: % @ ", [NSThread currentThread]); }}@ end

There are two types of calls in the master controller: synchronous and asynchronous.

/********************* 1. run the command directly and synchronize ***************/CustomOpertaionTest * operation = [[CustomOpertaionTest alloc] init]; // start the execution task [operation start]; execution result: 16:24:27. 620 NSOperationTest [3368: 222036] This is a test: <NSThread: 0x7ff420d28000> {number = 1, name = main}/********************** 2. add to queue, asynchronous ****************/NSOperationQueue * operationQueue = [[NSOperationQueue alloc] init]; customOpertaionTest * operation = [[CustomOpertaionTest alloc] init]; [operationQueue addOperation: operation]; execution result: 16:27:13. 594 NSOperationTest [3401: 225178] This is a test: <NSThread: 0x7ff2d0539d70 >{ number = 2, name = (null )}

Iii. Other common methods

 1) cancel the operation. After operation starts, the operation will be executed until the operation is completed by default. We can also call the cancel Method to cancel the operation in the middle.

[operation cancel];

There is a problem here: our custom operation. If cancellation is supported, you should query the reloaded main function to see if the user has canceled the operation, in particular, the main function must be queried when it is cyclical. Then release the resource and exit the main function.

2) If you want to do something after an NSOperation task is executed

Operation. completionBlock = ^ () {// after all operations are completed };

3) set the maximum number of concurrent threads. By default, the maximum number of concurrent threads is 6, that is, at the same time, only six threads can be in the ready state.

// The maximum number of concurrent operations is 3 [operationQueue setMaxConcurrentOperationCount: 3];

4) You can set dependencies to ensure the execution sequence. If you want operation A to be executed, you can perform Operation B as follows:

[operationB addDependency:operationA]; 

But be sure not to rely on B for A, and then B for A, so that both A and B cannot be executed. If A and B are in different operation queues, you can set dependencies.

 

Related Article

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.