IOS development-multithreading NSOperation and NSOperationQueue

Source: Internet
Author: User

IOS development-multithreading NSOperation and NSOperationQueue
NSThread can intuitively control thread objects, but it requires you to manage the thread lifecycle and thread synchronization by yourself, which is cumbersome to use and error-prone. However, Apple provides its own solution NSOperation, which itself is an abstract base class. Therefore, its subclass must be used. The NSOperation subclass can be used in NSInvocationOperation or NSBlockOperation, the usage of NSThread: NSThread obtains the current thread: [NSThread currentThread] msmselectorinbackground can update the UI. We do not recommend using:-(IBAction) update :( id) sender {[self defined mselectorinbackground: @ selector (changeImage) withObject: nil];} image background update:-(void) changeImage {NSLog (@ "Update image after thread execution"); self. myImageView. image = [UIImage ImageNamed: [NSString stringWithFormat: @ "Thread2.jpg"];} both NSInvocationOperation and NSBlockOperation methods are simple. The NSInvocation method is similar to NSThread, NSBlockOperation can be used if you have a little understanding of the Block. If you do not understand it, refer to my previous Block Article Object-C-code Block review. The following method is simple: first, let's take a look at the NSInvocationOperation instantiation method: // initialize NSInvocationOperation * myInvocationOperation = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (operationTaskMetho D) object: nil]; // start [myInvocationOperation start]; call method:-(void) operationTaskMethod {NSLog (@ "NSInvocationOperation initialization execution");} NSBlockOperation method: NSBlockOperation * blockOperation = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "BlockOperation block execution") ;}]; [blockOperation start, in this case, you can use NSOperationQueue as a queue to include threads. First, define a NSOperationQuene: @ property (strong, nonatomic) NSOperationQueue * myOpe RationQuene; at this time, call: required * operator = [[NSInvocationOperation alloc] OPERATOR: self selector: @ selector (operationTaskMethod) object: nil]; NSBlockOperation * blockOperation = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "BlockOperation block execution") ;}]; self. myOperationQuene = [[NSOperationQueue alloc] init]; [self. myOperationQuene addOperation: myInvocationOperation]; [se Lf. myOperationQuene addOperation: blockOperation]; The final result above is uncertain, and the thread execution sequence cannot be determined. If you want to confirm the execution in order, you need to add a dependency: [blockOperation addDependency: myInvocationOperation]; after adding the dependency, the output result must be as follows: 07:56:13. 457 ThreadDemo [657: 15033] NSInvocationOperation initialization execution 07:56:13. 457 ThreadDemo [657: 15034] BlockOperation the block executes the custom NSOperation. Every time you see the custom, you will feel that you have an instant grade. Then, refer to your previous experience, however, it is hard to say that some blogs on the Internet feel like I just want to eat a chicken leg. I actually got a chicken leg fort and I don't need it. All of them must be absorbed together. NSInvocationOperation and NSBlockOperation cannot meet business needs. In this case, you need to customize NSOperation. There are two types of customization: NonConcurrent and Concurrent) this article introduces non-concurrent formats. Create a new MyCustomOperation inherited from NSOperation, and then implement the main method: // MyCustomOperation. h // ThreadDemo // Created by keso on 15/2/11. // Copyright (c) 2015 keso. all rights reserved. // # import <Foundation/Foundation. h> @ interface MyCustomOperation: NSOperation @ property (strong, nonatomic) NSString * customdata;-(void) initData :( NSString *) data; @ end NSOperation the object needs to call the isCancelled method regularly to check whether the operation has been canceled. If YES (indicating that the operation has been canceled) is returned Immediately exit and recycle memory resources. All NSOperation subclasses are generally used in areas where the code is easily terminated. During each iteration of a loop, if each iteration is relatively long, it may need to be called multiple times or before execution. //// MyCustomOperation. m // ThreadDemo /// Created by keso on 15/2/10. // Copyright (c) 2015 keso. all rights reserved. // # import "MyCustomOperation. h "@ implementation MyCustomOperation-(void) initData :( NSString *) data {if (self = [super init]) _ customdata = data;}-(void) main {@ try {BOOL isDone = NO; NSLog (@ "call before loop"); while (! [Self isCancelled] &! IsDone) {// Do some work and set isDone to YES when finished NSLog (@ "already running successfully"); isDone = YES ;}} @ catch (...) {NSLog (@ "exception occurred. Check the code ~ ") ;}}@ End: MyCustomOperation * customOperation = [[MyCustomOperation alloc] init]; [customOperation Start];

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.