iOS multi-threaded custom operation loading pictures do not repeat download pictures

Source: Internet
Author: User

Abstract: 1:ios encapsulates gcd with an abstract class nsoperation, making iOS multithreading easier and easier to use;

2: Time-consuming operations are given to child threads to complete, the main thread is responsible for UI processing, prompting the user's experience

2: Custom operation inherit from nsoperation, download picture in sub-thread;

3: Ensure that images are downloaded only once, and that download tasks are not duplicated

------------------------------------------------------------------------------------

Implementation principle: 1: Picture cache: Save pictures and pictures in a dictionary Url,key:url value: image

2: Task cache: Save the Url,key:url of operation tasks and pictures in a dictionary value:operation

See the custom operation:.h file first

1 #import<Foundation/Foundation.h>2 @classxboperation;3 4 @protocolXboperationdelegate <NSObject>5 6-(void) Operation: (Xboperation *) operation Didfinishdownloadimage: (UIImage *) image;7 8 @end9 /**Ten * Custom Operation One  */ A @interfacexboperation:nsoperation -  - //Agent the@property (nonatomic, weak)ID<XBOperationDelegate>Delegate; -  - /** - * URL +  */ -@property (nonatomic, copy) NSString *URL; + /** A * cells in Indexpath and TableView correspond to at  */ -@property (nonatomic, strong) Nsindexpath *Indexpath; -  - @end

Description: The purpose of setting up the agent is to wait for the controller to take pictures after the download picture is finished.

Custom operation. m files

@implementationxboperation-(void) main{if(self.iscancelled)return; Nsurl*downloadurl =[Nsurl URLWithString:self.url]; NSData*data = [NSData Datawithcontentsofurl:downloadurl];//This guild is time consuming .        if(self.iscancelled)return; UIImage*image =[UIImage Imagewithdata:data]; if(self.iscancelled)return; NSLog (@"--%@--", [Nsthread CurrentThread]); if([Self.Delegaterespondstoselector: @selector (operation:didfinishdownloadimage:)]) {Dispatch_async (Dispatch_get_main_queue (),^{//back to the main thread, pass the picture data to the proxy object[Self.Delegateoperation:self Didfinishdownloadimage:image];    }); }}@end

Description: Overriding the Main method, when the task operation is added to the queue, the queue automatically invokes the task's Start method, and the Start method calls the main method to complete the operation

Implementation of Tableviewcell data source for controller

#pragmaMark DataSource Data Source Method-(Nsinteger) Numberofsectionsintableview: (UITableView *) tableview{return 1;}-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{returnSelf.apps.count;}//the data source method implements the content padding in the cell-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{StaticNSString *id =@"app"; UITableViewCell*cell =[TableView Dequeuereusablecellwithidentifier:id]; if(!cell) {Cell=[[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault Reuseidentifier:id]; }    //Setting the data Xbapp is the data modelXbapp *app =Self.apps[indexpath.row]; //set Title and sub-headingsCell.textLabel.text =App.name; Cell.detailTextLabel.text=App.download; Cell.imageView.image= [UIImage imagenamed:@"57437179_42489b0"]; //Picture Data SettingsUIImage *image =Self.imagecache[app.icon]; if(image) {//If there is a picture in the picture cache loaded directly intoCell.imageView.image =image; }Else{//If there is no data in the cache//Set placeholder image firstCell.imageView.image = [UIImage imagenamed:@"57437179_42489b0"]; //Create a custom operation first from the queue based on the URL that is currently showing the picture operation see if the download is in progressXboperation *operationdown =Self.operationqueue[app.icon]; if(!operationdown) {//Create and add to queue if download operation does not existOperationdown =[[Xboperation alloc] init]; Operationdown.Delegate= self;//Set up proxyOperationdown.indexpath = Indexpath;//bind each cell to a operationOperationdown.url =App.icon; //adding operation to the queue automatically calls the Start method and then calls operation's Main method[Self.queue Addoperation:operationdown]; //add operation this download task to the Operation dictionary to prevent duplicate downloadsSelf.operationqueue[app.icon] =Operationdown; }        }            returncell; }//Implementing Proxy Methods-(void) Operation: (Xboperation *) operation Didfinishdownloadimage: (UIImage *) image{//It must be clear that the current operation prevent download failures due to network and other reasons operation still in the dictionary so never download[Self.operationqueue RemoveObjectForKey:operation.url]; if(image) {//put the picture in the cache dictionarySelf.imagecache[operation.url] =image; //Refresh table row refreshes[Self.tableview Reloadrowsatindexpaths:@[operation.indexpath] withrowanimation:uitableviewrowanimationnone]; }}

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.