iOS multithreaded--nsoperation

Source: Internet
Author: User
Tags gcd

Nsoperation is a set of multithreaded implementations based on GCD, and like GCD, the life cycle of a thread is managed automatically by the system, without having the programmer manage it manually like Nsthread and Pthread. Compared to GCD, it is more object-oriented, and more than gcd more simple and practical functions, in addition, because its API is pure OC, by the majority of programmers love, practical frequency is very high.

Nsoperation the main and nsoperationqueue use to implement multi-threading, the general steps are as follows:

1. Encapsulate the required action into a Nsoperation object first;

2. Then add the Nsoperation object to the Nsoperationqueue;

3. The system will automatically take out the nsoperation in the Nsoperationqueue;

4. Put the removed nsoperation into one thread to execute.

Note: Nsoperation is an abstract class that does not have the ability to encapsulate operations and must use its subclasses. There are three ways to use the Nsoperation subclass:

1.NSInvocationOperation

2.NSBlockOperation

3. Customize the subclass inheritance Nsoperation to implement the internal corresponding method.

Let's look at the first two types:

First, Nsoperation:

1- (void) Viewdidload {2 [Super Viewdidload];3 [self invocationoperation];4 }5 6-(void) Invocationoperation7 {8     9     //1. Create an Action object to seal the task that needs to be performedTenNsinvocationoperation *operation = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (DOWNLOAD1)Object: nil]; One      A     //2. Perform the action (by default, if the action is not placed in the action queue, it is executed synchronously) - [Operation start]; - } the  --(void) Download1 - { -NSLog (@"Download 1----%@", [Nsthread CurrentThread]); +}

The results are as follows:

As you can see, by default, if the action is not placed in the operations queue, it is executed synchronously in the main thread, and only nsoperation is executed asynchronously in Nsoperationqueue.

Second, nsblockoperation

1- (void) Viewdidload {2 [Super Viewdidload];3 [self blockoperation];4 }5 6- (void) Blockoperation7 {8Nsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^{9NSLog (@"nsblockoperation--Download 1---%@", [Nsthread CurrentThread]);Ten     }]; One      A[Operation addexecutionblock:^{ -NSLog (@"nsblockoperation--Download 2---%@", [Nsthread CurrentThread]); -     }]; the      -[Operation addexecutionblock:^{ -NSLog (@"nsblockoperation--Download 3---%@", [Nsthread CurrentThread]); -     }]; + [Operation start]; -}

Results

We will find that nsblockoperation, when there is only a single task, is executed by default on the main thread, and when the number of tasks is greater than 1, the child threads are opened and other operations are performed concurrently .

Third, with the use of Nsoperationqueue

1- (void) Viewdidload {2 [Super Viewdidload];3 [self operationqueue];4 }5 6- (void) Operationqueue7 {8Nsinvocationoperation *operation1 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (DOWNLOAD1)Object: nil];9Nsinvocationoperation *operation2 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (download2)Object: nil];TenNsinvocationoperation *operation3 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (DOWNLOAD3)Object: nil]; OneNsblockoperation *operation4 = [Nsblockoperation blockoperationwithblock:^{ ANSLog (@"nsblockoperation--1---%@", [Nsthread CurrentThread]); -     }]; -[Operation4 addexecutionblock:^{ theNSLog (@"nsblockoperation--2---%@", [Nsthread CurrentThread]); -     }]; -Nsoperationqueue *queue =[[Nsoperationqueue alloc] init]; - [Queue Addoperation:operation1]; + [Queue Addoperation:operation2]; - [Queue Addoperation:operation3]; + [Queue addoperation:operation4]; A } at-(void) Download1 - { -NSLog (@"Download 1----%@", [Nsthread CurrentThread]); - } --(void) Download2 - { inNSLog (@"Download 2----%@", [Nsthread CurrentThread]); - } to-(void) Download3 + { -NSLog (@"Download 3----%@", [Nsthread CurrentThread]); the}

The results are as follows

As you can see, as long as the operation is added to the Nsoperationqueue, the system will automatically open the child threads for us to execute, and is a concurrent unordered execution, independent of the order of addition.

However, there are times when we need to explicitly specify the order of operations, and we can set dependencies between nsoperation to guarantee the order of execution.

For example, Operation 1 to execute after Operation 2, you can write: [Operation1 adddependency:operation2] means that Operation1 relies on operation2, Which is operation1 to execute behind Operation2.

Under Code Validation:

1- (void) Viewdidload {2 [Super Viewdidload];3 [self operationqueue];4 }5 6- (void) Operationqueue7 {8Nsinvocationoperation *operation1 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (DOWNLOAD1)Object: nil];9Nsinvocationoperation *operation2 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (download2)Object: nil];TenNsinvocationoperation *operation3 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (DOWNLOAD3)Object: nil]; OneNsoperationqueue *queue =[[Nsoperationqueue alloc] init]; A [Operation3 Adddependency:operation1]; - [Operation1 Adddependency:operation2]; - [Queue Addoperation:operation1]; the [Queue Addoperation:operation2]; - [Queue Addoperation:operation3]; - } --(void) Download1 + { -NSLog (@"Download 1----%@", [Nsthread CurrentThread]); + } A-(void) Download2 at { -NSLog (@"Download 2----%@", [Nsthread CurrentThread]); - } --(void) Download3 - { -NSLog (@"Download 3----%@", [Nsthread CurrentThread]); in}

The results are as follows:

The sequence of operations Operation2->operation1->operation3, exactly right, is actually who relies on who, who is executed behind it

Alternatively, you can set dependencies between nsoperation of different queue

Sequence of operations: 4->3->2->1 remaining two concurrent executions

Some of the properties and methods of Nsoperationqueue are listed below:

1.-(void) Cancelalloperations all operations to cancel the queue. PS: You can also call the Nsoperation-(void) Cancel method to cancel a single operation

[Email protected] (getter=issuspended) BOOL suspended; Yes means the queue is paused, no indicates a reply queue

[Email protected] Nsinteger Maxconcurrentoperationcount; Represents the maximum number of concurrent, typically not greater than 5

Iv. Custom Nsoperation

When you add a custom nsoperation to Nsoperationqueue, the system calls the Nsoperation-(void) Main method, so we just need to override this method to implement the corresponding implementation.

1-(void) Main2 {3@autoreleasepool {//an asynchronous thread cannot access the main thread's auto-free pool and needs to add it itself4         if(self.iscancelled)return;//whether the monitoring operation is canceled, if the cancellation is returned5Nsurl *url =[Nsurl URLWITHSTRING:SELF.MATCHURL];6         if(self.iscancelled)return;7NSData *data =[NSData Datawithcontentsofurl:url];8         if(self.iscancelled)return;9UIImage *image =[UIImage Imagewithdata:data];Ten         if([_delegate respondstoselector: @selector (operation:finsheddownloadimage:)]) { OneDispatch_async (Dispatch_get_main_queue (), ^{//updating the UI on the main thread A[Self.Delegateoperation:self Finsheddownloadimage:image]; -             }); -         } the     } -}

Note that the main thread cannot access the auto-free pool of the main thread, so you need to add it yourself.

Here is a small demo, custom Nsoperation to implement an asynchronous download of the picture, and to avoid repeating the same image download

iOS multithreaded--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.