iOS Development Multithreading Chapter 11-Custom Nsoperation

Source: Internet
Author: User
Tags uikit

iOS Development multithreaded article-Custom nsoperation

First, to achieve a simple tableview display effect

Implementation results show:

code example (using a previous way of doing business with the host controller)

1. Create a new project to inherit the controller from Uitableviewcontroller.

1//2//  YYViewController.h 3//  01-Custom Operation 4//5//  Created by Apple on 14-6-26.6//  Copyright (c ) 2014 itcase. All rights reserved. 7//8  9 #import <uikit/uikit.h>10 @interface yyviewcontroller:uitableviewcontroller12 @end

2. Handle the storyboard interface as follows:

3. According to plist file, dictionary to model

Create a new class that inherits from NSObject, as a model of the data

YYappModel.h file

1//2//  YYappModel.h 3//  01-Custom Operation 4//5//  Created by Apple on 14-6-26.6//  Copyright (c) 2014 Year Itcase. All rights reserved. 7//8  9 #import <foundation/foundation.h>10 @interface yyappmodel:nsobject12/**13  * App name  @ */15 @ Property (nonatomic,copy) nsstring *name;16/**17  *  application picture  */19 @property (nonatomic,copy) NSString * Icon;20/**21  *  app download amount  */23 @property (nonatomic,copy) nsstring *download;24 + (instancetype) Appmodelwithdict: (nsdictionary *) dict;26-(Instancetype) Initwithdict: (nsdictionary *) dict;27 @end

YYAPPMODEL.M file

1//2//  YYAPPMODEL.M 3//  01-Custom Operation 4//5//  Created by Apple on 14-6-26.6//  Copyright (c) 2014 Year Itcase. All rights reserved. 7//8  9 #import "YYappModel.h" @implementation YYappModel12-(Instancetype) Initwithdict: (Nsdictionary *) dict14 {     Self=[super init] {         [self setvaluesforkeyswithdictionary:dict];17     }18 return self     ; 19}20 21//factory method + (Instancetype) appmodelwithdict: (Nsdictionary *) dict23 {     return [[Self alloc]initwithdict: Dict];25}26 @end

Logical control part of the master controller, YYVIEWCONTROLLER.M file

 1//2//YYVIEWCONTROLLER.M 3//01-Custom Operation 4//5//Created by Apple on 14-6-26. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYappModel.h" @interface Yyviewcontroller () @property (nonatomic, Strong) Nsarray *apps;14 @end16 @implementation YYViewController18 #pragma mark-lazy load-(Nsarray *) APPS20 { (_apps==nil) {nsstring *path=[[nsbundle mainbundle]pathforresource:@ "apps.plist" oftype:nil];23 NSArray *tempArray=[ Nsarray arraywithcontentsoffile:path];24 25//dictionary to model Nsmutablearray *array=[nsmutablearray array]             ; nsdictionary *dict in Temparray) {Yyappmodel *app=[yyappmodel appmodelwithdict:dict];29 [Array addobject:app];30}31 _apps=array;32}33 return _apps;34}35 #pragma mark-data source Party FA Notoginseng-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section38 {return self.apps.count;40}41-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexPath43 {nsstring static *[email protected] "ID"; UITableViewCell *cell=[tableview Dequeuereusablec ellwithidentifier:id];46 if (cell==nil) {Cell=[[uitableviewcell alloc]initwithstyle:uitableviewcellstylesub     Title reuseidentifier:id];48}49 Yyappmodel *app=self.apps[indexpath.row];50 cell.textlabel.text=app.name;51     CELL.DETAILTEXTLABEL.TEXT=APP.DOWNLOAD;52 53//Download image data NSLog (@ "Load image data---%@", [Nsthread CurrentThread]); 55 Nsurl *url=[nsurl urlwithstring:app.icon];56 nsdata *data=[nsdata datawithcontentsofurl:url];57 UIImage *imgae =[uiimage imagewithdata:data];58 cell.imageview.image=imgae;59 NSLog (@ "Finish display"), return cell;61}62 @end

Print View:

Second, custom nsoperation

Description: The above download image data section is a very time-consuming operation, this operation task is completed in the main thread, it will seriously affect the user experience, causing the phenomenon of the UI card. Following the custom nsoperation, the new thread lets the task of loading the picture execute asynchronously.

1. By proxy

Based on the above, create a new class that inherits from Nsoperation.

YYdownLoadOperation.h file

1//2//  YYdownLoadOperation.h 3//  01-Custom Operation 4//5//  Created by Apple on 14-6-26.6//  Copyright (c) Itcase 2014. All rights reserved. 7//8  9 #import <foundation/foundation.h>10 #pragma mark-set agent and proxy method @class yydownloadoperation;13 @ Protocol Yydownloadoperationdelegate <nsobject>14-(void) Downloadoperation: (yydownloadoperation*) operation Didfisheddownload: (UIImage *) image;15 @end16 @interface yydownloadoperation:nsoperation18 @property (nonatomic, copy) NSString *url;19 @property (nonatomic,strong) Nsindexpath *indexpath;20 @property (nonatomic,strong) ID < Yydownloadoperationdelegate> delegate;21 @end

YYDOWNLOADOPERATION.M file

1//2//  YYDOWNLOADOPERATION.M 3//  01-Custom Operation 4//5//  Created by Apple on 14-6-26.6//  Copyright (c) Itcase 2014. All rights reserved. 7//8  9 #import "YYdownLoadOperation.h" @implementation YYdownLoadOperation12-(void) main13 {     Nsurl *url =[nsurl urlwithstring:self.url];15     nsdata *data=[nsdata datawithcontentsofurl:url];16     UIImage *imgae=[ UIImage imagewithdata:data];17     NSLog (@ "--%@--", [Nsthread CurrentThread]);     notify Agent 20 when the picture is downloaded     if ([Self.delegate respondstoselector: @selector (downloadoperation:didfisheddownload:)]) {         Dispatch_ Async (Dispatch_get_main_queue (), ^{//back to the main thread, passing data to the proxy object              [Self.delegate downloadoperation:self Didfisheddownload:imgae];23         });     }25}26 @end

Business logic in the host controller:

 1//2//YYVIEWCONTROLLER.M 3//01-Custom Operation 4//5//Created by Apple on 14-6-26. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYappModel.h" #import "YYdownLoadOperation.h" @interface Yyviewco Ntroller () <yydownloadoperationdelegate>14 @property (nonatomic,strong) nsarray *apps;15 @property (nonatomic, Strong) Nsoperationqueue *queue;16 @end18 @implementation YYViewController20 #pragma mark-lazy load apps21-(Nsarray *) app         S22 {_apps==nil) {nsstring *path=[[nsbundle mainbundle]pathforresource:@ "Apps.plist" oftype:nil];25 Nsarray *temparray=[nsarray arraywithcontentsoffile:path];26 27//Dictionary to model Nsmutablearray * Array=[nsmutablearray array];29 for (nsdictionary *dict in Temparray) {Yyappmodel *app=[yyappmodel appmodelwithdict:dict];31 [Array addobject:app];32}33 _apps=array;34}35 return _apps ; 36}37#pragma mark-lazy load queue39-(Nsoperationqueue *) Queue40 {if (_queue==nil) {_queue=[[nsoperationqueue All OC]INIT];43//Set maximum concurrency of 344 _queue.maxconcurrentoperationcount=3;45}46 return _queue;47}48 #pra     GMA mark-Data Source Method-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section51 {52 Return self.apps.count;53}54-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: ( Nsindexpath *) indexPath55 {nsstring *[email protected] "ID"; UITableViewCell *cell=[tableview dequ euereusablecellwithidentifier:id];58 if (cell==nil) {Cell=[[uitableviewcell Alloc]initwithstyle:uitableview Cellstylesubtitle reuseidentifier:id];60}61 Yyappmodel *app=self.apps[indexpath.row];62 cell.textLabel.text=a pp.name;63 cell.detailtextlabel.text=app.download;64 65//Download image Data//NSLog (@ "Load picture data---%@", [Nsthread Curre Ntthread]); Nsurl *url=[nsurl Urlwithstring:app.icon];68//NSData *data=[nsdata datawithcontentsofurl:url];69//UIImage *imgae=[uiimage imageWithData:d ATA];70//CELL.IMAGEVIEW.IMAGE=IMGAE;71 72//Create a Operation object Yydownloadoperation *operation=[[yydownload      Operation Alloc]init];74 operation.url=app.icon;75 operation.indexpath=indexpath;76 operation.delegate=self;77  78//Add the operand to the queue in the go to [self.queue addoperation:operation];80 Bayi//NSLog (@ "complete display"); the return cell;83}84 -(void) Downloadoperation: (yydownloadoperation *) operation Didfisheddownload: (UIImage *) Image85 {86// Returns the picture data to each row corresponding to the cell's imageview.image87//Take out TableView Indexpath This line corresponds to the cell88 UITableViewCell *cell=[self.tableview CELLF orrowatindexpath:operation.indexpath];89//Show image cell.imageview.image=image;91//NSLog (@ "cell--index--%@---%@ ", Operation.indexpath,[nsthread CurrentThread]); 92//Be sure to refresh the table. [Self.tableview reloaddata];94 NSLog (@"--%@--", [Nsthread CurrentThread]); }97 @end 

Description: The above code can be found to be a big problem by printing.

Issue 1: You need to ensure that a URL corresponds to a Operation object.

Issue 2: Removal is required after download. Removes the completed operation.

Issue 3: Ensure that a URL corresponds to an image. The code in the host controller is improved:
  1//2//YYVIEWCONTROLLER.M 3//01-Custom Operation 4//5//Created by Apple on 14-6-26. 6//Copyright (c) 2014 itcase.  All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYappModel.h" #import "YYdownLoadOperation.h" @interface YY Viewcontroller () <YYdownLoadOperationDelegate> @property (nonatomic,strong) Nsarray *apps; @property (Nonatomic,strong) Nsoperationqueue *queue; @property (Nonatomic,strong) nsmutabledictionary *operations; @property (Nonatomic,strong) nsmutabledictionary *images; @end @implementation yyviewcontroller #pragma mark-lazy load apps-(Nsarray *) Apps (_apps==ni L) {nsstring *path=[[nsbundle mainbundle]pathforresource:@ "Apps.plist" Oftype:nil]; Nsarray *tempAr Ray=[nsarray Arraywithcontentsoffile:path]; 28 29//Dictionary to model Nsmutablearray *array=[nsmutablearray array]; (Nsdictionary *dict in Temparray) {yyappmOdel *app=[yyappmodel Appmodelwithdict:dict]; [Array Addobject:app]; _apps=array}; The PNS return _apps; Max #pragma mark-lazy load queue-(Nsoperationqueue *) Queue (_queue==nil) {_queue=[[nsopera Tionqueue Alloc]init]; 45//Set maximum concurrency of 3 _queue.maxconcurrentoperationcount=3; _queue return;         $ #pragma mark-lazy load operations-(Nsmutabledictionary *) operations (_operations==nil) {55 _operations=[nsmutabledictionary dictionary]; _operations; (mark-) #pragma lazy load images-(Nsmutabledictionary *) images (_images==nil) {+-_images=[n Smutabledictionary dictionary]; (+})-return _images; #pragma mark-Data source method (Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) Section Self.apps.count {The Return of the "UITableViewCell") TableView: (UITableView*) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath (nsstring) "ID"; 77 UITableViewCell *cell=[tableview Dequeuereusablecellwithidentifier:id]; if (cell==nil) {Cell=[[uitableviewcell alloc]initwithstyle:uitableviewcellstylesubtitle reuseIdentifier : ID]; Yyappmodel *app=self.apps[indexpath.row]; Cell.textlabel.text=app.name; Cell.detailtextlabel.text=app.download; 84 85//Ensure a URL corresponds to an Image object. UIImage *image=self.images[app.icon];         if (image) {//cache There are pictures in cell.imageview.image=image;}else//No pictures in the cache, download 90 {91 First set up a placeholder picture cell.imageview.image=[uiimage imagenamed:@ "57437179_42489b0"]; Yydownloadoperation *operation=self.operations[app.icon]; 94 if (operation) {//Downloading 95//do nothing}else//Currently no download, then create the operation, {98 Ope Ration=[[yydownloadoperation Alloc]init];           99  operation.url=app.icon;100 operation.indexpath=indexpath;101 operation.delegate=self;102 [Self.queue addoperation:operation];//asynchronous Download 103 self.operations[app.icon]=operation;104}105}1 107 108 Return cell;109}110-(void) Downloadoperation: (yydownloadoperation *) operation Didfisheddownload: (UIIma GE *) image111 {112//1. Remove the completed Operation 113 [Self.operations removeobjectforkey:operation.url];114 115//2. Put the picture in the cache self.images[operation.url]=image;117 118//3. Refresh the table (refresh only the downloaded row) 119 [Self.tableview Reloadrowsatindex Paths:@[operation.indexpath] withrowanimation:uitableviewrowanimationautomatic];121 NSLog (@ "--%d--%@--", Operation.indexpath.row,[nsthread CurrentThread]); 122 123}124 @end

Print View:

iOS Development Multithreading Chapter 11-Custom Nsoperation

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.