iOS development-multithreaded nsoperation and Nsoperationqueue

Source: Internet
Author: User

The previous article mentioned a little bit about the use of nsthread, Nsthread can intuitively control the thread object, but need to manage the thread's life cycle, thread synchronization, use it more cumbersome, and more prone to error. However, Apple has given its own solution nsoperation, which is itself an abstract base class, so it must use its subclasses, and the way to use the Nsoperation subclass is Nsinvocationoperation and Nsblockoperation two ways to first add the use of Nsthread:

Nsthread Gets the current thread:

[Nsthread CurrentThread]

Performselectorinbackground can update the UI, it is not recommended to use:

-(ibaction) Update: (ID) Sender {    [self performselectorinbackground: @selector (changeimage) withobject:nil];    }

Picture background update:

-(void) changeimage{    NSLog (@ "Update picture after thread Execution");    Self.myimageview.image=[uiimage imagenamed:[nsstring stringwithformat:@ "thread2.jpg"];}
Nsinvocationoperation and Nsblockoperation

Both of these methods are simple, where nsinvocation is called in a way similar to nsthread,nsblockoperation if you have a little understanding of block, if you do not understand can refer to my previous block article object-c-Block review, the next way to use it is simple:

First look at the instantiation of the nsinvocationoperation:

    Initialize    nsinvocationoperation *myinvocationoperation= [[nsinvocationoperation alloc] initwithtarget:self Selector : @selector (Operationtaskmethod) Object:nil];    Start    [myinvocationoperation start];

Call Method:

-(void) operationtaskmethod{    NSLog (@ "nsinvocationoperation initialization Execution");    }

Nsblockoperation the way:

  Nsblockoperation *blockoperation=[nsblockoperation blockoperationwithblock:^{        NSLog (@ "blockOperation block Execution");    }];    [blockoperation start];

Two ways are convenient, this time you can use Nsoperationqueue as a queue to include threads together, first define a nsoperationquene:

@property (strong,nonatomic) Nsoperationqueue *myoperationquene;

This time you need to call:

    Nsinvocationoperation *myinvocationoperation= [[nsinvocationoperation alloc] initwithtarget:self selector: @selector (Operationtaskmethod) Object:nil];        Nsblockoperation *blockoperation=[nsblockoperation blockoperationwithblock:^{        NSLog (@ "blockOperation block Execution");    }];    Self.myoperationquene=[[nsoperationqueue Alloc]init];        [Self.myoperationquene addoperation:myinvocationoperation];        [Self.myoperationquene addoperation:blockoperation];

The final result is indeterminate, the order of the threads is not determined, and if you want to determine the order of execution, you need to add a dependency:

    [Blockoperation adddependency:myinvocationoperation];

After adding the dependencies, the result of each output must be this:

2015-02-11 07:56:13.457 threaddemo[657:15033] nsinvocationoperation Initialize execution 2015-02-11 07:56:13.457 ThreadDemo[ 657:15034] Blockoperation block execution
Custom Nsoperation

every time you see a custom, feel an instant has a grade, and then refer to the previous experience, but online blog some bad say, it feels like I just want to eat a chicken leg, did get a chicken leg fort, need not need to be absorbed together. nsinvocationoperation and nsblockoperation These two ways can not meet the business requirements, this time need to customize the nsoperation, custom has two types of non-concurrency ( Nonconcurrent) and Concurrent (Concurrent) forms, this article describes non-concurrency.

Create a new mycustomoperation that inherits 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

The Nsoperation object needs to periodically call the IsCancelled method to detect if the operation has been canceled, and if it returns Yes (which means it has been canceled), immediately exits execution of the reclaimed memory resource. All nsoperation subclasses, typically used for code comparisons where it is easier to terminate, are called during each iteration of the loop, if each iteration is relatively long and may need to be called multiple times and no work is performed.

  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 works and set IsDone to YES when finished            NSLog (@ "has run successfully"); 
   isdone=yes;        }    }    @catch (...) {        NSLog (@ "Exception occurred, please check code ~");}    } @end

If you need to invoke the defined Nsoperation instantiation, start:

   Mycustomoperation *customoperation=[[mycustomoperation alloc] init];    [Customoperation start];

 Reference: https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ Operationobjects/operationobjects.html#//apple_ref/doc/uid/tp40008091-ch101-sw6

iOS development-multithreaded nsoperation and Nsoperationqueue

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.