OC Language Knowledge 4

Source: Internet
Author: User

Directory of this document

    • Objective
    • First, Nsinvocationoperation
    • Second, nsblockoperation
    • Iii. Other uses of nsoperation
    • Iv. Custom Nsoperation
Back to the top of the preface

1. The previous talk briefly introduced the use of nsthread, although it can also achieve multithreaded programming, but we need to manage the thread's life cycle, but also to consider thread synchronization, locking problems, resulting in some performance overhead. We can also implement multithreaded programming with Nsoperation and Nsoperationqueue, which is basically the following:

1> first encapsulates the action that needs to be performed into a Nsoperation object

2> then add the Nsoperation object to the Nsoperationqueue

The 3> system automatically places the encapsulated action in the nsoperation into a new thread to execute

In this process, we do not have to consider the thread life cycle, synchronization, locking and other issues

Here is an example of a scenario, such as a list of followers of Weibo:

Each line of the avatar must be downloaded from the Sina server image before it can be displayed, and it is necessary to download the asynchronous. At this time you can take each line of the picture download operation encapsulated in a Nsoperation object, there are 6 rows, so to create 6 nsoperation objects, and then add to Nsoperationqueue, respectively download a different picture, after downloading, Return to the corresponding row of the picture displayed.

2. By default, Nsoperation does not have the ability to encapsulate operations, it must use its subclasses, and there are 3 ways to use nsoperation subclasses:

1> nsinvocationoperation

2> nsblockoperation

3> Custom subclass Inherits Nsoperation, implements the internal corresponding method

This first describes how to encapsulate an operation with Nsoperation, followed by a combination of nsoperationqueue to use.

Back to the top one, nsinvocationoperation
1 nsinvocationoperation *operation = [[[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (run:) object:@ "MJ"] autorelease];2 [operation start];

* Line 1th Initializes a Nsinvocationoperation object that is based on an object and selector to create an action

* Line 2nd invokes the Start method, immediately following the encapsulated operation, which calls Self's run: method, and @ "MJ" as the method parameter

* Note here: 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.

Go back to the top two, NSBlockOperation1. Perform an operation synchronously
1 nsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^ () {2         NSLog (@ "performed a new Operation"); 3}];4  / /start to perform task 5 [Operation start];

* Line 1th Initializes a Nsblockoperation object that uses a block to encapsulate what needs to be done

* Line 2nd invokes the Start method and immediately executes the contents of the block

* This is still performed synchronously on the current thread and is not executed asynchronously

2. Concurrent execution of multiple operations
1 nsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^ () {2 NSLog (@ "Perform 1th operation, thread:%@", [Nsthread Curr Entthread]); 3}]; 4  5 [Operation addexecutionblock:^ () {6 NSLog (@ "performed 1 new operations, Thread:%@", [Nsthread CurrentThread]); 7}]; 8  9 [Operation addexecutionblock:^ () {NSLog (@) performed 1 new operations, Thread:%@ ", [Nsthread CurrentThread]);}];12 [Operatio n addexecutionblock:^ () {NSLog (@ "performed 1 new operations, Thread:%@", [Nsthread CurrentThread]); 15}];16 17//Start the task [Operation Star T];

* Line 1th Initializes a Nsblockoperation object

* in lines 5th, 9 and 13, the new operation was added by Addexecutionblock: method, including the operation of Line 1th, which encapsulates 4 operations.

* After the Start method is called on line 18th, the 4 operations are executed concurrently, which is executed in different threads

1 2013-02-02 21:38:46.102 thread[4602:c07] performed 1 new operations, Thread: <nsthread:0x7121d50>{name = (null), num = 1}2 2013-02-02 2 1:38:46.102 thread[4602:3f03] Performed 1 new operations, Thread: <nsthread:0x742e1d0>{name = (null), num = 5}3 2013-02-02 21:38:46.102 THREAD[4602:1B03] Performs the 1th operation, thread: <nsthread:0x742de50>{name = (null), num = 3}4 2013-02-02 21:38:46.102 thread[ 4,602:1303] 1 new operations executed, thread: <nsthread:0x7157bf0>{name = (null), num = 4}

As you can see, the NUM values for each operation thread are different, indicating that

Back to top Iii. other usages of nsoperation 1. Cancel operation

After the operation has started executing, the operation continues until it is completed, and we can call the Cancel method halfway through the operation

[Operation Cancel];

2. Do something after the operation is done

If you want to do something after a nsoperation has finished executing, call Nsoperation's Setcompletionblock method to set what you want to do.

Operation.completionblock = ^ () {    NSLog (@ "execution complete");};

When the operation encapsulated operation is completed, the contents of the block are recalled

Back to top four, custom nsoperation

If Nsinvocationoperation and nsblockoperation do not meet the requirements, we can inherit the nsoperation directly from the new subclass and add any actions that need to be performed. If you simply customize the nsoperation, you only need to overload-(void) Main, in this method, add the action that needs to be performed.

Write the sub-class downloadoperation to download the picture below

1. Inherit nsoperation, overriding the Main method DownloadOperation.h
#import <Foundation/Foundation.h> @protocol downloadoperationdelegate; @interface downloadoperation: nsoperation//Image URL Path @property (nonatomic, copy) NSString *imageurl;//agent @property (nonatomic, assign) id< Downloadoperationdelegate> delegate;-(ID) Initwithurl: (nsstring *) URL delegate: (Id<downloadoperationdelegate >) delegate; protocol for @end//Picture Download @protocol downloadoperationdelegate <nsobject>-(void) Downloadfinishwithimage: ( UIImage *) image; @end
Downloadoperation.m
1 #import "DownloadOperation.h" 2  3 @implementation downloadoperation 4 @synthesize delegate = _delegate; 5 @synthesiz e imageUrl = _imageurl; 6  7//Initialize 8-(ID) Initwithurl: (nsstring *) URL delegate: (id<downloadoperationdelegate>) Delegate {9     if ( self = [Super init]) {         Self.imageurl = url;11         self.delegate = delegate;12     }13     return self;14}15//Free memory -(void) Dealloc {     [super dealloc];18] [     _imageurl release];19}20 21//Executive Director-(void) Main {     //create a new automatic Frees the pool, and if it is executed asynchronously, it will not be able to access the automatic release pool of the main thread     @autoreleasepool {         //....     }27}28 @end

* The Main method is overloaded in line 22nd, and then the code to download the image is written in this method

* If this downloadoperation is performed in an asynchronous thread, that is, the main method is invoked on an asynchronous thread, the main thread's auto-free pool will not be accessible, so the 24th row creates an auto-release pool that belongs to the current thread

2. Correct response to cancellation events

* By default, when a nsoperation starts executing, it will perform the task until the end, such as the above Downloadoperation, which will execute all the code in the main method by default.

* Nsoperation provides a Cancel method to cancel the current operation.

* If it is a custom nsoperation, this cancellation event needs to be handled manually. For example, once the Cancel method is called, the execution of the main method should be terminated immediately and some resources will be recovered in a timely manner.

* The practice of handling cancellation events is to call the IsCancelled method periodically in the main method to detect if the operation has been canceled, that is, if the Cancel method is called, and if Yes is returned, the main method is returned immediately.

* The following places may need to call the IsCancelled method:

    • Before any actual work is performed, that is, at the beginning of the main method. Because cancellation can occur at any time, even before operation is executed.
    • After performing a time-consuming operation, it is also necessary to detect whether the operation has been canceled
1-(void) Main {2     //Create a new auto-free pool, if it is an asynchronous operation, you will not have access to the main thread's auto-free Pool 3     @autoreleasepool {4 if         (self.iscancelled) Return 5          6         //Get Picture Data 7         nsurl *url = [Nsurl URLWITHSTRING:SELF.IMAGEURL]; 8         NSData *imagedata = [NSData datawithc Ontentsofurl:url]; 9         if (self.iscancelled) {one             url = nil;12             imageData = nil;13             return;14         }15         16         //Initialize picture         UIImage *image = [UIImage imagewithdata:imagedata];18         if (self.iscancelled) {             image = Nil;21             return;22         }23         if ([Self.delegate respondstoselector: @selector (downloadfinishwithimage:)]) {25             //Transfer the image data back to the main             thread [(NSObject *) self.delegate performselectoronmainthread: @selector (downloadfinishwithimage:) withobject:image waituntildone:no];27         }28     }29}

* In line 4th, the main method begins by judging if operation has been canceled. If it's canceled, there's no need to carry it down.

* After the 8th line to download the picture, in line 10th also need to determine whether the operation has been canceled

* In short, after a relatively time-consuming operation, it is necessary to determine whether the operation has been canceled

* After the picture is downloaded, the image data is passed to the proxy (delegate) object in the 26th row

OC Language Knowledge 4

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.