[IOS] backend work queue: nsoperationqueue, nsoperation, nsinvocationoperation

Source: Internet
Author: User

Nsoperationqueue

1. In operationqueue, should I be able to add multiple operations at the same time?

Yes. The purpose of operationqueue is multi-thread management.NoIt is just a thread.

In addition, we can set the number of "operations" processed by this queue each time.

NSOperationQueue *aQ = [[NSOperationQueue alloc] init];[aQ setMaxConcurrentOperationCount:10];

Here, setmaxconcurrentoperationcount is the "operand" to be processed at the same time. The parameters are integer Int or nsinteger (the two are the same. You can search for them in my blog ~)

2. How should I write the main function?

In the main function, you only need to write what you want to do in another process. For example, for me, I often just do a simple task. Then I will use the simplified version of nsinvocationoperation and nsoperation. For example:

Nsinvocationoperation * aopt = [[nsinvocationoperation alloc] initwithtarget: Self selector: @ selector (dosomething) object: Nil];-(void) dosomething {// Read a large amount of delayed data    // You can use javasmselecdomainmainthread to return the obtained data to the main thread.}

In the dosomething function, I can read something from the Internet, but reading takes time and blocks the main thread. Using nsoperation will not work.

If it is nsoperation, although complicated, it is also a subclass of nsoperation. In fact, the main function does the same thing as dosomething. However, if you create this subclass, you can perform more operations on it, make more complex read and load operations, and you can reuse this class function. In addition, nsoperation also provides support for runtime operations, but it is too troublesome.


Nsoperation

Multi-threaded programming is the best way to prevent the main thread from being congested and increase the running efficiency. The original multi-threaded method has many problems, including thread locking. In cocoa, Apple provides the nsoperation class and an excellent multi-threaded programming method.

The following describes how to use nsoperation:

1. Separate the job in another thread into a class and set its parent class to nsoperation:

@ Interface imageloadingoperation: nsoperation {nsurl * imageurl;// In this example, an image address needs to be input, so an nsurl variable is defined.Id target;// Because some values need to be returned, an object parameter is required to return the object to be returned (Class Object running this thread)Sel action;// Method function to be stimulated by the return value}

2. Use its initialization method to pass in the required parameters and objects

-(ID) initwithimageurl :( nsurl *) theimageurl target :( ID) thetarget action :( SEL) theaction {self = [Super init];// Explains why this is required in the old post.If (Self) {imageurl = [theimageurl retain];// Copy the object and retain (why? Check the old post)Target = thetarget; Action = theaction;} return self ;}

When calling this class object, pass in the required parameters and objects

// These are the code in the class to be initializedImageloadingoperation * operation = [[imageloadingoperation alloc] initwithimageurl: URL target: Self action: @ selector (didfinishloadingimagewithresult :)];// Initialization[Operationqueue addoperation: Operation];// Add to the running queue[Operation release];// Because the queue has retain for it, we need to release it

3. The work required for main function execution in our thread operation class

-(Void) Main {// Load the image at the same timeNsdata * Data = [[nsdata alloc] initwithcontentsofurl: imageurl]; uiimage * image = [[uiimage alloc] initwithdata: Data];// Return the package to the initial class object and perform the specified operationNsdictionary * result = [nsdictionary attributes: image, imageresultkey, imageurl, urlresultkey, nil]; [target attributes mselec1_mainthread: Action withobject: Result waituntildone: No]; [data release];// Clear it if you do not need it[Image release];}

These are a simple nsoperation process. Actually, it's very simple, just like other APIs Apple has prepared for us!

Nsinvocationoperation

Multi-threaded programming is the best way to prevent the main thread from being congested and increase the running efficiency. The original multi-threaded method has many problems, including thread locking. In cocoa, Apple provides the nsoperation class and an excellent multi-threaded programming method.

This section describes the subset of nsoperation and nsinvocationoperation of the simple method:

@ Implementation mycustomclass-(void) launchtaskwithdata :( ID) Data {// Create an nsinvocationoperation object and initialize it to the Method    // Here, the value after the selector parameter is the method (function, method) You want to run in another thread)    // Here, the object value is the data to be passed to the previous method.Nsinvocationoperation * theop = [[nsinvocationoperation alloc] initwithtarget: Self selector: @ selector (mytaskmethod :) object: Data];// Add the operation "operation" we created to the shared queue of the local program (the method will be executed immediately after the operation is added)    // In more cases, we create an "operation" queue by ourselves.[[Myappdelegate implements doperationqueue] addoperation: theop];}// This is the "method" that actually runs in another thread"-(Void) mytaskmethod :( ID) Data {// Perform the task.} @ End

An nsoperationqueue operation queue is equivalent to a thread manager rather than a thread. Because you can set the number of threads that can run in parallel in this thread manager. The following describes how to create and initialize an operation queue:

@ Interface myviewcontroller: uiviewcontroller {nsoperationqueue * operationqueue;// Declare the queue in the header file} @ End @ implementation myviewcontroller-(ID) Init {self = [Super init]; If (Self) {operationqueue = [[nsoperationqueue alloc] init];// Initialize the operation queue[Operationqueue setmaxconcurrentoperationcount: 1];// This limits the queue to run only one thread at a time        // This queue is ready for use.} Return self;}-(void) dealloc {[operationqueue release];// As Alan often said, we are a good citizen of the program and need to release the memory![Super dealloc];} @ end

After a brief introduction, we can find that this method is very simple. In many cases, multithreading is only used to prevent main thread congestion, and nsinvocationoperation is the simplest multi-threaded programming, which is often used in iPhone programming.

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.