iOS Development Multithreading Basics Nsoperation

Source: Internet
Author: User

-------nsoperation Introduction----The role of 1.NSOperation • With the use of nsoperation and nsoperationqueue can also achieve multi-threaded programming 2.NSOperation and nsoperationqueue multi-threaded implementation of the specific steps · Wrap the action you need to perform into a Nsoperation object • Then add the Nsoperation object to the Nsoperationqueue • The system automatically places the actions encapsulated in the nsoperation in a new threadSubclass of---------nsoperation----3.NSOperation is an abstract class and does not have the ability to encapsulate operations, it must use its subclass 4. There are 3 ways to use the Nsoperation subclass · Nsinvocationoperation Nsblockoperation Custom Subclass Inherits Nsoperation, implements the internal corresponding method------nsinvocationoperation---5. Create a Nsinvocationoperation object

-(ID) Initwithtarget: (ID) Target selector: (SEL) Sel object: (ID) arg;

6. Call the Start method to start the operation

-(void) start;

Once the operation is performed, the Sel method of the target is called

7. Note • 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 • Operations are performed asynchronously only if the nsoperation is placed in a nsoperationqueue-------nsblockoperation--8. Create a Nsblockoperation object

+ (ID) Blockoperationwithblock: (void (^) (void)) block;

9. Add more actions by Addexecutionblock: method

-(void) Addexecutionblock: (void (^) (void)) block;

Note: The operation is performed asynchronously as long as the nsblockoperation encapsulated operand > 1

-------Nsoperationqueue----

The role of 10.NSOperationQueue · Nsoperation can invoke the Start method to perform a task, but it is performed synchronously by default • If you add nsoperation to the Nsoperationqueue (action queue), the system automatically executes operation 11 in Nsoperation. Adding actions to Nsoperationqueue

-(void) Addoperation: (Nsoperation *) op;

-(void) Addoperationwithblock: (void (^) (void)) block;

-------Maximum number of concurrent----

12. What is concurrency • Number of simultaneous tasks • For example, 3 threads are executing 3 tasks simultaneously, and the concurrency count is 3 13. Correlation method of maximum concurrency number

-(Nsinteger) Maxconcurrentoperationcount;

-(void) Setmaxconcurrentoperationcount: (Nsinteger) CNT;

-----The cancellation, pause, resume------of a queue

14. Cancel all operations on a queue

-(void) cancelalloperations;

Tip: You can also call the Nsoperation-(void) Cancel method to cancel a single operation

15. Pausing and resuming queues

-(void) setsuspended: (BOOL) b; Yes means pause queue, no for recovery queue

-(BOOL) issuspended;

----Operation Priority-----

16. Set the priority of the nsoperation in the queue to change the order in which the operations are executed

-(nsoperationqueuepriority) queuepriority;

-(void) Setqueuepriority: (nsoperationqueuepriority) p;

17. The priority value (the higher the priority, the more the first execution) · Nsoperationqueuepriorityverylow = -8l, Nsoperationqueueprioritylow = -4l, Nsoperationqueueprioritynormal = 0, Nsoperationqueuepriorityhigh = 4, Nsoperationqueuepriorityveryhigh = 8---operation dependent---A dependency can be set between 18.NSOperation to guarantee the order of execution • For example, make sure that operation A is done before you can perform operation B, so write

[Operationb Adddependency:operationa]; Action B depends on action a

19. You can create a dependency between nsoperation of different queue

Note: cannot depend on each other

• For example a relies on b,b dependency a----The execution order of the operation---21. For operations added to the queue, the order in which they are executed depends on 2 points • First depending on the dependency between nsoperation • Then according to the priority of the Nsoperation 22. Therefore, the overall order of execution is first to satisfy the dependencies · Then choose the highest-priority execution from the nsoperation.---custom nsoperation---23. The steps to customize the nsoperation are simple • Rewrite-(void) The Main method, where you implement the task that you want to perform 24. overriding-(void) The note point of the Main method • Create an auto-free pool yourself (because if it is an asynchronous operation, you cannot access the auto-free pool of the main thread) · Often pass-(BOOL) IsCancelled method detects whether the operation is canceled, responds to cancellation--------Split line---nsoperation small code 1, write only one file reference
dyfviewcontroller.m//624-03-nsoperation////Created by dyf on 14-6-24.//Copyright (c) 2014 ___fullusername___. All rights reserved.//#import "DYFViewController.h" @interface Dyfviewcontroller () @end @implementation dyfviewcontroller-(void) viewdidload{[Super viewdidload];//do any additional setup after loading the view, typically          From a nib. [Self testoperationqueue];} -(void) Testoperationlisten {nsblockoperation *operation3 = [nsblockoperation blockoperationwithblock:^{NSLog (        @ "Download picture 1111111%@", [Nsthread CurrentThread]);    Download picture}];    Operation3.completionblock = ^{//Download the picture after the time you want to do};    2. Create queue Nsoperationqueue *queue = [[Nsoperationqueue alloc] init]; [Queue Addoperation:operation3];} -(void) Testoperationqueue {//1. Encapsulation operation nsinvocationoperation *operation1 = [[Nsinvocationoperation alloc] Initwithta    Rget:self selector: @selector (download) Object:nil]; Nsinvocationoperation *operation2 = [[Nsinvocationoperation alloc]Initwithtarget:self selector: @selector (run) Object:nil]; Nsblockoperation *operation3 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "1111111%@", [NSThread currentTh    Read]);        }];    [Operation3 addexecutionblock:^{NSLog (@ "222222%@", [Nsthread CurrentThread]);    }];    [Operation3 addexecutionblock:^{NSLog (@ "33333%@", [Nsthread CurrentThread]);    }];    2. Create queue Nsoperationqueue *queue = [[Nsoperationqueue alloc] init]; Within 5, the appropriate queue.maxconcurrentoperationcount = 2; #warning face question//set operation dependencies (be sure to set before adding to the queue) [Operation2 Adddependenc Y:operation1]; The order of execution depends on the dependency, first executing the operation1 and then executing operation2//Note: Cannot depend on each other, loop operation//3. Add an action to the queue (auto-execute, auto-open thread) [Queue Addoperation:opera    Tion1];    [Queue Addoperation:operation2];        [Queue Addoperation:operation3];        Cancel all threads//[queue Cancelalloperations];        Pause queue//[queue Setsuspended:yes];       Set operation priority//operation1.queuepriority = Nsoperationqueuepriorityveryhigh; }-(void) Testnsblockoperation {//1. Create an Action object that encapsulates the task to be performed nsblockoperation *operation = [Nsblockoperation blockoperation        withblock:^{for (int i = 0; i <; i++) {NSLog (@ "1111111%@", [Nsthread CurrentThread]);    }    }]; The number of tasks above 2, will be the thread [Operation addexecutionblock:^{for (int i = 0; i < one; i++) {NSLog (@ "222222%@")        , [Nsthread CurrentThread]);    }    }]; [Operation addexecutionblock:^{for (int i = 0; i <; i++) {NSLog (@ "33333%@", [Nsthread currentthr        EAD]);    }    }]; 2. Perform the operation [operation start];} -(void) Testnsinvocationoperation {//1. Create an Action object that encapsulates the task to be performed nsinvocationoperation *operation = [[Nsinvocationoperation    Alloc] initwithtarget:self selector: @selector (download) Object:nil]; 2. Perform the operation (by default, if the operation is not placed in the queue, it will be performed synchronously) [Operation start];}    -(void) download{for (int i = 0; i <; i++) {NSLog (@ "Download-----%@", [Nsthread CurrentThread]); }}-(void) run{for (int i = 0; I < 11;    i++) {NSLog (@ "Run------%@", [Nsthread CurrentThread]); }} @end

----Custom Nsoperation---

  dyfdownloadoperation.h//  624-05-Custom operation////  Created by dyf on 14-6-24.//  Copyright (c) 2014 DYF. All rights reserved.//#import <Foundation/Foundation.h> @class dyfdownloadoperation; @protocol Dyfdownloadoperationdelegate <NSObject> @optional-(void) Downloadoperation: (dyfdownloadoperation *) operation Didfinisheddownload: (UIImage *) image; @end @interface dyfdownloadoperation:nsoperation@property (nonatomic, copy) NSString *url; @property (nonatomic, strong) Nsindexpath *indexpath; @property (nonatomic, weak) id< Dyfdownloadoperationdelegate> delegate; @end

  dyfdownloadoperation.m//  624-05-Custom operation////  Created by dyf on 14-6-24.//  Copyright (c) 2014 DYF. All rights reserved.//#import "DYFDownloadOperation.h" @implementation dyfdownloadoperation/** *  to implement specific actions in the Main method * /-(void) main{    @autoreleasepool {        if (self.iscancelled) return;        Nsurl *imaurl = [Nsurl URLWithString:self.url];        if (self.iscancelled) return;        The following line is time consuming        nsdata *data = [NSData Datawithcontentsofurl:imaurl];        if (self.iscancelled) return;        UIImage *image = [UIImage imagewithdata:data];        if (self.iscancelled) return;                Returns the main thread display picture        //via proxy        if ([Self.delegate respondstoselector: @selector (downloadoperation: Didfinisheddownload:)] {            [self.delegate downloadoperation:self didfinisheddownload:image];}        }    @end

Use the MVC pattern to create a file of the old cliché, only a controller.m file for reference, data storage problems, you can use the Sdwebimage framework to handle

dyftableviewcontroller.m//624-05-Custom operation////Created by dyf on 14-6-24.//Copyright (c) 2014 ___fulluserna me___. All rights reserved.//#import "DYFTableViewController.h" #import "DYFAppModel.h" #import "DYFDownloadOperation.h" # Warning Dictionary basic knowledge not very understanding, dictionary assignment go back to see notes @interface Dyftableviewcontroller () <dyfdownloadoperationdelegate>@ Property (Nonatomic, Strong) Nsarray *apps; @property (nonatomic, strong) nsoperationqueue *queue;/** * Key:url value:op Eration Object */@property (nonatomic, strong) nsmutabledictionary *oprations;/** * Key:url value:image Object */@property (Nonat Omic, strong) nsmutabledictionary *images; @end @implementation dyftableviewcontroller#pragma mark-4 Lazy Loading-(NSArray *)        apps{if (!_apps) {NSString *path = [[NSBundle Mainbundle] pathforresource:@ "apps" oftype:@ "plist"];                Nsarray *arrayapps = [Nsarray Arraywithcontentsoffile:path];        Nsmutablearray *arraym = [Nsmutablearray arrayWithCapacity:arrayApps.count]; for (NSDIctionary *dict in Arrayapps) {Dyfappmodel *appm = [Dyfappmodel appwithdict:dict];        [Arraym addobject:appm];    } _apps = Arraym; } return _apps;}        -(Nsoperationqueue *) queue{if (!_queue) {_queue = [[Nsoperationqueue alloc] init];    Set the maximum number of concurrent threads and download up to 3 images at the same time _queue.maxconcurrentoperationcount = 3; } return _queue;}    -(Nsmutabledictionary *) oprations{if (!_oprations) {_oprations = [[Nsmutabledictionary alloc] init]; } return _oprations;}    -(Nsmutabledictionary *) images{if (!_images) {_images = [nsmutabledictionary dictionary]; } return _images;} -(void) viewdidload{[Super viewdidload];//do no additional setup after loading the view, typically from a nib.} #pragma mark-Data source Method-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{return s Elf.apps.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (NSINDEXPATH *) INDexpath{//1. Create cell static NSString *identifier = @ "apps";    UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:identifier]; if (!cell) {cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstylesubtitle Reuseidentifier:identifier]    ;    }//2. Set the cell's data Dyfappmodel *app = Self.apps[indexpath.row];    Cell.textLabel.text = App.name;        Cell.detailTextLabel.text = App.download; The point is how to download images from the network into the cell above//each URL corresponds to a Dyfdownloadoperation object//Each URL corresponds to an image object UIImage *image = self.images[app.i    Con];    if (image) {//If a picture is present in the cache cell.imageView.image = image; }else {//If a picture is not present in the cache, the picture will be downloaded from the Web//set before the system is downloaded cell.imageView.image = [UIImage imagenamed:@ "ID small"]                ;        Base difference, the following line does not understand dyfdownloadoperation *operation = Self.oprations[app.icon]; if (operation) {//If you are downloading, do not perform other actions}else {//If not downloaded, create a child thread to start the download dyfdownload Operation *Operation = [[Dyfdownloadoperation alloc] init];            Operation.url = App.icon;            Operation.indexpath = Indexpath;            Operation.delegate = self;            Add task into queue, asynchronous download [Self.queue addoperation:operation];        The base is poor, the following line does not understand self.oprations[app.icon] = operation; }}//3. Return to cell return cell;} #pragma mark-dyfdownloadoperationdelegate-(void) Downloadoperation: (dyfdownloadoperation *) operation    Didfinisheddownload: (UIImage *) image{//1. Delete the completed download operation [Self.oprations RemoveObjectForKey:operation.url];        If the picture is downloaded good if (image) {///2. Save the downloaded picture in cache self.images[operation.url] = image; 3. Refresh the data for this row of cells [Self.tableview Reloadrowsatindexpaths:@[operation.indexpath] Withrowanimation:uitableviewrowani        Mationnone];        4. Save picture into Sandbox//4.1 picture first convert to 2 binary data nsdata *data = uiimagepngrepresentation (image); 4.2 Set sandbox path nsstring *path = [[NssearchpathfordirectoriesIndomains (NSDocumentDirectory, Nsuserdomainmask, YES) Lastobject] stringbyappendingpathcomponent:[self.apps[        Operation.indexPath.row] [icon]];        NSLog (@ "%@", Path);    4.3 Save data to path [data Writetofile:path Atomically:yes]; }}//start dragging when the queue is paused-(void) scrollviewwillbegindragging: (Uiscrollview *) scrollview{[Self.queue Setsuspended:yes];} Restart queue when dragging is stopped-(void) scrollviewwillenddragging: (Uiscrollview *) ScrollView withvelocity: (cgpoint) Velocity Targetcontentoffset: (inout cgpoint *) targetcontentoffset{[Self.queue setsuspended:no];} @end

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.