<span id="Label3"></p><p><p>the <span style="font-size:12px">download of the previous article was placed in the block, when the complex operation, a bunch of code in the block, it is clear that this is not a wise choice, the code seems very bloated. therefore, The threading operation is placed in the custom Nsoperation. </span></p></p><p><p><span style="font-size:12px"><br></span></p></p><p><p></p></p><p class="p1"><p class="p1"><span style="font-size:12px"><span class="s1">Custom</span> <span class="s2">nsoperation</span> <span class="s1">the steps: inherit nsoperation,</span> <span class="s1">rewrite</span> <span class="s2">-(</span><span class="s3">void</span><span class="s2">) main</span> <span class="s1">method in which you implement the task you want to perform. </span></span></p></p><p class="p1"><p class="p1"><span style="font-size:12px"><span class="s1"></span> <span class="s1">override</span> <span class="s2">-(</span><span class="s3">void</span><span class="s2">) The main</span> <span class="s1">method's note point:</span></span></p></p><p class="p1"><p class="p1"><span style="font-size:12px"><span class="s1">1</span> . Create an Auto-free pool yourself (because If it is an asynchronous operation, you cannot access the main Thread's auto-free pool).</span></p></p><p class="p1"><p class="p1"><span style="font-size:12px">2, <span class="s1">often through</span> the <span class="s2">-(</span><span class="s3">BOOL</span><span class="s2">) iscancelled</span> <span class="s1">method to detect whether the operation was canceled, to respond to the Cancellation. </span></span></p></p><p class="p1"><p class="p1"><span class="s1"><span style="font-size:12px"><br></span></span></p></p><p class="p1"><p class="p1"><span style="font-size:12px">Case Code:</span></p></p><p class="p1"><p class="p1"><span style="font-size:12px">1, The new downloadoperation inherits nsoperation, the download operation puts in the main method. As for the download back to the main thread to do something, it itself does not know (not its scope of work). Only responsible for the download after the notification to other people, so entrusted to the agent, <span style="font-family:Helvetica Neue,Helvetica,STheiti,微软雅黑,黑体,Arial,Tahoma,sans-serif,serif; color:#252525"> <span style="line-height:28px; background-color:rgb(250,250,250)">entrusted to others to do things. </span></span></span></p></p><p class="p1"><p class="p1"><span style="font-family:Helvetica Neue,Helvetica,STheiti,微软雅黑,黑体,Arial,Tahoma,sans-serif,serif; color:#252525"><span style="line-height:28px; background-color:rgb(250,250,250)"><span style="font-size:10px">DownloadOperation.h</span><br></span></span></p></p><p class="p1"><p class="p1"><span class="s1"></span></p></p><pre code_snippet_id="1560673" snippet_file_name="blog_20160121_1_2383726" name="code" class="objc"><pre code_snippet_id="1560673" snippet_file_name="blog_20160121_1_2383726" name="code" class="objc">#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @class downloadoperation;//protocol @protocol Downloadoperationdelegate <NSObject> @optional-(void) downloadoperation: (downloadoperation *) operation Didfinishdownload: (UIImage *) image; @end @interface downloadoperation:nsoperation//download image address @property (nonatomic,copy) NSString *imageurl;//table Cell location @property (nonatomic,strong) nsindexpath *indexpath;//agent @property (nonatomic,weak) ID <DownloadOperationDelegate> delegate; @end</pre></pre><br><br><p><p></p></p><p class="p1"><p class="p1"><span class="s1">Downloadoperation.m</span></p></p><p class="p1"><p class="p1"><span class="s1">Note: @autoreleasepool <span style="font-size:12px">The Auto-free pool, the<span class="s2" style="font-size:12px">iscancelled</span> <span class="s1" style="font-size:12px">Method detects whether the operation is canceled, and responds to the Cancellation. </span></span><br></span></p></p><p class="p1"><p class="p1"><span class="s1"></span></p></p><pre code_snippet_id="1560673" snippet_file_name="blog_20160121_2_9984937" name="code" class="objc"><pre code_snippet_id="1560673" snippet_file_name="blog_20160121_2_9984937" name="code" class="objc">#import "DownloadOperation.h" #import <UIKit/UIKit.h> @implementation downloadoperation-(void) main{ @ Autoreleasepool {//manage Memory if (self.iscancelled) return; Pauses the operation for execution nsurl *url = [nsurl URLWithString:self.imageUrl]; NSData *data = [nsdata datawithcontentsofurl:url]; Download UIImage *image = [UIImage imagewithdata:data];//nsdata-UIImage if (self.iscancelled) return;// Pauses the operation being performed //back to the main thread [[nsoperationqueue mainqueue] addoperationwithblock:^{ if ([self.delegate Respondstoselector: @selector (downloadoperation:didfinishdownload:)]) { [self.delegate downloadoperation: Self didfinishdownload:image];}} ];} } @end</pre></pre><br><br><p><p></p></p><p class="p1"><p class="p1"><span class="s1">2, APPSTABLEVIEWCONTROLLER.M</span></p></p><p class="p1"><p class="p1"><span class="s1"> </span> </p> </p><pre code_snippet_id="1560673" snippet_file_name="blog_20160121_3_5143151" name="code" class="objc">Appstableviewcontroller.m//cell picture Download (custom operation) #import "AppsTableViewController.h" #import "App.h" #import " DownloadOperation.h "@interface Appstableviewcontroller () <downloadoperationdelegate>//application information collection @property ( Nonatomic,strong) nsmutablearray *apps;//the queue to store all downloaded images @property (nonatomic,strong) nsoperationqueue *queue;// Store all download operations (url is Key,operation object is Value) @property (nonatomic,strong) nsmutabledictionary *operations;// Store all downloaded images @property (nonatomic,strong) nsmutabledictionary *images; @end @implementation appstableviewcontroller-( Void) viewdidload {[super viewdidload]; }-(void) didreceivememorywarning {[super didreceivememorywarning]; Dispose of any resources the can be recreated.} /** * Lazy load **/-(nsmutablearray *) apps{if (!_apps) {nsmutablearray *apparr = [nsmutablearray array]; NSString *file =[[nsbundle mainbundle] pathforresource:@ "apps" oftype:@ "plist"]; Nsarray *dictarr = [nsarray arraywithcontentsoffile:file]; For (nsdictionary *dict in dictarr) {app *app = [app appwithdict:dict]; [apparr addobject:app]; } _apps = apparr; } return _apps;} -(nsoperationqueue *) queue{if (!_queue) {_queue = [[nsoperationqueue alloc]init]; } return _queue;} -(nsmutabledictionary *) operations{if (!_operations) {_operations = [[nsmutabledictionary alloc]init]; } return _operations;} -(nsmutabledictionary *) images{if (!_images) {_images = [[nsmutabledictionary alloc]init]; } return _images;} #pragma mark-table View data source-(nsinteger) numberofsectionsintableview: (uitableview *) tableView {return 1;} -(nsinteger) tableView: (uitableview *) tableView numberofrowsinsection: (nsinteger) section {return self.apps.count;} -(uitableviewcell *) tableView: (uitableview *) tableView cellforrowatindexpath: (nsindexpath *) indexpath {static Nsstri ng *id = @ "app"; UITableViewCell *cell = [tableView dequeuereusablecellwithidentifier:id];If (!cell) {cell = [[uitableviewcell alloc]initwithstyle:uitableviewcellstylesubtitle reuseidentifier:id]; } App *app = self.apps[indexpath.row]; Cell.textLabel.text = app.name; Cell.detailTextLabel.text = app.download; The image URL corresponding to the UIImage UIImage *image = self.images[app.icon] is taken from the images cache first; If (image) {//description picture has been successfully downloaded (successfully cached) cell.imageView.image = image; }else{//get caches path, Stitching file path nsstring *file = [nssearchpathfordirectoriesindomains (nscachesdirectory, nsus erdomainmask, YES) lastobject] Stringbyappendingpathcomponent:[app.icon lastpathcomponent]; First remove the picture from the sandbox nsdata *data = [nsdata datawithcontentsoffile:file]; If there is a picture in the If (data) {//sandbox cell.imageView.image = [UIImage imagewithdata:data]; }else{//sandbox does not exist, for download operation//display placeholder picture cell.imageView.image = [UIImage imagenamed:@ "placeholder"]; Download Image [self Download:app.icon Indexpath:indexpath]; }} return cell;} -(void) download: (nsstring *) imageUrl indexpath: (nsindexpath *) indexpath{//take out the download operation under the current picture URL (operations Object) Download Operation *operation = self.operations[imageurl]; If (operation) return; If there is an action that does not go down (because the picture download operation may be in progress)//create operation, download picture operation = [[downloadoperation alloc]init]; Operation.imageurl = imageUrl; Operation.indexpath = indexpath; Set Proxy operation.delegate = self; Adding operations to the queue [self.queue addoperation:operation]; Added to the dictionary (this code in order to resolve the duplicate download) self.operations[imageurl] = operation; }/** * Call */-(void) scrollviewwillbegindecelerating When the user starts to drag the table: (uiscrollview *) scrollview{//pause Download [self.queue setsuspen ded:yes];} /** * Call */-(void) scrollviewdidenddecelerating when the user stops dragging the table: (uiscrollview *) scrollview{//start Download [self.queue setsuspende d:no];} #pragma mark-agent method for download Operation-(void) downloadoperation: (downloadoperation *) operation Didfinishdownload: (UIImage *) image{/ /store picture in dictionary if (image) { Store all download Operations self.operations[operation.imageurl] = image; Save the picture in a sandbox nsdata *data = uiimagepngrepresentation (image); NSString *file = [[nssearchpathfordirectoriesindomains (nscachesdirectory, nsuserdomainmask, YES) lastObject] Stringbyappendingpathcomponent:[operation.imageurl lastpathcomponent]]; [data Writetofile:file atomically:yes]; }//remove the download operation from the dictionary (to prevent operations from getting larger, to ensure that the download fails, can be downloaded Again) [self.operations removeObjectForKey:operation.imageUrl]; Refresh Table [self.tableview reloadrowsatindexpaths:@[operation.indexpath] Withrowanimation:uitableviewrowanimationnone ];} @end</pre><br><br><p><p></p></p><p class="p1"><p class="p1"><span class="s1"><br></span></p></p><p class="p1"><p class="p1"><span class="s1"></span></p></p><br><p><p>iOS Development practice cell download Picture (custom Nsoperation)</p></p></span>
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.