IOS ----- use NSOperation and NSOperationQueue to implement multithreading and nsoperationqueue

Source: Internet
Author: User

IOS ----- use NSOperation and NSOperationQueue to implement multithreading and nsoperationqueue
Multithreading using NSOperation and NSOperationQueue

The basic theories of NSOperation and NSOperationQueue are as follows.

NSOperationQueue

A fifo queue is used to manage multiple NSOperation submitted by the system. The NSOperationQueue maintains a thread pool at the underlying layer and starts the thread to execute the NSOperation task submitted to the queue in sequence.

NSOperation

Represents a multi-threaded task. NSOperation has two subclasses: NSInvocationOperation and NSBlockOperation. NSOperation can be used in two ways: ① The developer implements the NSOperation subclass; ② the developer directly uses the NSInvocationOperation or NSBlockOperation subclass.

Using NSOperation and NSOperationQueue to develop multithreading is very simple, as long as the following two steps

1

Create an NSOperationQueue queue and set relevant attributes for the queue.

2

Create an NSOperation subclass object and submit it to the NSOperationQueue queue. Each NSOperation is enabled in sequence.

NSOperationQueue is responsible for managing and executing all NSOperation tasks. It maintains a thread pool at the underlying layer. NSOperation submitted by developers is executed by the threads in the thread pool. NSOperationQueue provides the following common methods.

 
 
     
Use NSInvocationOperation and NSBlockOperation

Both NSInvocationOperation and NSBlockOperation are subclasses of NSOperation and can be directly used in programs to encapsulate tasks that require asynchronous execution.

NSInvocationOperation and NSBlockOperation are very similar in usage. The difference is that NSInvocationOperation is used to encapsulate specific methods of a specific object into NSOperation, while NSBlockOperation is used to encapsulate code into NSOperation.

The code snippet for creating NSInvocationOperation is as follows:

 

The code snippet for creating NSBlockOperation is as follows:

 

Once the NSOperation object is obtained, submit the NSOperation object to the NSOperationQueue.

Example: Use NSBlockOperation to download images

The following is the implementation code of the View Controller class of the instance.

1 @ implementation ViewController 2 3 NSOperationQueue * queue; 4 5-(void) viewDidLoad 6 7 {8 9 [super viewDidLoad]; 10 11 queue = [[NSOperationQueue alloc] init]; 12 13 // set this queue to support a maximum of 10 concurrent threads 14 15 queue. maxConcurrentOperationCount = 10; 16 17} 18 19-(IBAction) clicked :( id) sender20 21 {22 23 NSString * url = @ "limit 25 // use the incoming code block as the execution body, create NSOperatio N26 27 NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {28 29 // obtain data from the network 30 31 NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: url]; 32 33 // initialize network data to a UIImage object 34 35 UIImage * image = [[UIImage alloc] initWithData: data]; 36 37 if (image! = Nil) 38 39 {40 41 // run updateUI in the main thread: Method 42 43 [self defined mselecw.mainthread: @ selector (updateUI :) 44 45 withObject: image waithUntilDone: YES]; // ① 46 47} 48 49 else50 51 {52 53 NSLog (@ "--- An error occurred while downloading the image ---"); 54 55} 56 57}]; 58 59 // Add NSOperation to NSOperationQueue60 61 [queue addOperation: operation]; 62 63} 64 65-(void) updateUI :( UIImage *) image66 67 {68 69 self. iv. image = image; 70 71} 72 73 @ end

 

This program creates an NSBlockOperation object, and then submits the object to NSOperationQueue. the code block will be executed in the thread. Therefore, the program calls javasmselecw.mainthread: withObject: waitUntilDone in code ①: The method updates the image displayed by the iv Control in the main thread.

Define NSOperation subclass

NSOperation is generally not used directly. Instead, it is used to create a subclass of NSOperation. To create a subclass of NSOperation, you must override the method-(void) main. The method is used as the task completed by NSOperationQueue.

The following program demonstrates how to use the NSOperation subclass to download network images. The interface for this example is similar to the interface for downloading images using NSThread, but this program uses NSOperation subclass to start multi-thread download. In this example, only one UIImageView and one UIButton are displayed. The program binds clicked to the "Touch Up Inside" time of UIButton: event processing method.

The following is the code of the LCDownImageOperation class interface.

Generation

Code

Slice

Segment

1 LCDownLoadImageOperation. h文2 2 3 # import <Foundation/Foundation. h> 4 5 // define NSOperation subclass 6 7 @ interface LCDownImageOperation: NSOperation 8 9 @ property (nonatomic, strong) NSURL * url; 10 11 @ property (nonatomic, weak) UIImageView * imageView; 12 13-(id) initWithURL :( NSURL *) url imageView :( UIImageView *) iv; 14 15 @ end16 17 LCDownLoadImageOperation. m file 18 19 @ implementation LCDownLoadImageOperation20 21- (Id) initWithURL :( NSURL *) url imageView :( UIImageView *) iv22 23 {24 25 self = [super init]; 26 27 if (self) 28 29 {30 31 _ imageView = iv; 32 33 _ url = url; 34 35} 36 37 return self; 38 39} 40 41 // rewrite the main method, this method will act as the thread execution body 42 43-(void) main44 45 {46 47 // obtain data from the network 48 49 NSData * data = [[NSData alloc] initWithContentsOfURL: self. url]; 50 51 // initialize network data to a UIImage object 52 53 UIImage * image = [[UIImage alloc] initWithData; da Ta]; 54 55 if (image! = Nil) 56 57 {58 59 // run updateUI in the main thread: Method 60 61 [self defined mselec1_mainthread: @ selector (updateUI :) 62 63 withObject: image waitUntilDone: YES]; // ① 64 65} 66 67 else68 69 {70 71 NSLog (@ "++ error occurred while downloading the image +++ "); 72 73} 74 75} 76 77-(void) updateUI :( UIImage *) image78 79 {80 81 self. imageView. image = image; 82 83} 84 85 @ end

 

Description

The code above creates a subclass of the NSOperation class and overwrites the main method. This method will be used as the execution body of the thread started by the NSOperation-that is, the task that represents the completion of the thread. because the code of the main method will be executed in the new thread, the program also calls the javasmselecw.mainthread: withObject: waitUntilDone: Method to update the image displayed by the iv Control in the main thread.

 

Code snippet

After creating the NSOperation subclass, you only need to create an instance for this subclass and submit it to NSOperationQueue. LCDownImageOperation is used to download images from the network. the following is the implementation code of the View Controller class.

1 ViewController. m 2 3 @ implementation ViewController 4 5 NSOperationQueue * queue; 6 7-(void) viewDidLoad 8 9 {10 11 [super viewDidLoad]; 12 13 queue = [[NSOperationQueue alloc] init]; 14 15 // set this queue to support a maximum of 10 concurrent threads 16 17 queue. maxConcurrentOperationCount = 10; 18 19} 20 21-(IBAction) clicked :( id) sender22 23 {24 25 // define the URL26 27 NSURL * url of the image to be loaded * [NSURL URLWithString: @ "http://img2.imgtn.bdimg.com/it/u=194240101,2532182839&fm=21&gp=0.j pg"]; 28 29 // create LCDownImageOperation object 30 31 LCDownImageOperation * operation = [[LCDownImageOperation alloc] initWithURL: url imageView: self. iv]; 32 33 // submit the instance of the NSOperation subclass to NSOperationQueue34 35 [queue addOperation: operation]; 36 37} 38 39 @ end

 

Description

The code in the above program is the key code for multi-threaded download using LCDownImageOperation. You only need to create an LCDownImageOperation instance and submit the instance to NSOperationQueue.

 

Summary

IOS provides three types of multithreading support: ① using NSThread to develop multi-threaded applications; ② using GCD to implement multithreading; ③ using NSOperation and NSOperationQueue to implement multithreading.

 

 

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.