IOS---tableview optimized lazy (lazy loading) mode and asynchronous load mode when loading images

Source: Internet
Author: User

For example, when we are using the NetEase news app, watching so much news, not all of us are interested in, sometimes we just quickly slip over, want to quickly skip the content that do not like, but as long as the slide through, the picture began to load, so the user experience is not very good, and waste memory.

This time, we can use lazy loading technology, when the interface sliding or sliding deceleration, do not do picture loading, only when the user no longer slide and slow down the effect of the time to load.

At first I loaded the image asynchronously using Sdwebimage to do, the final experiment when the use of the bug, because although the sdwebimage implementation of the asynchronous loading cache, when loading the picture after the request will be directly loaded cache pictures, note that the key to the, if it is lazy loading, The sliding process is not a network request, the image on the cell will be reused, when you stop to make a network request, it will change back to the current cell should be the picture, about 1-2 seconds delay (not counting the delay, is not the request, is not without the problem of caching). How to solve it? At this point we will define a UIImage property in the Model object, and after downloading the image asynchronously, use the image path already cached in the sandbox to assign it a value, so that the Cellforrowatindexpath method determines whether the UIImage object is empty, if it is empty , the network request, not empty, is directly assigned to the cell's ImageView object, so that it can be a good solution to the short-term image reuse problem.

@ Below My code is the asynchronous load cache class that I write, sdwebimage loading picture lazy loading, the principle is similar.

@model class #import <Foundation/Foundation.h> @interface newsitem:nsobject@property (nonatomic,copy) NSString * Newstitle; @property (nonatomic,copy) nsstring * newspicurl; @property (nonatomic,retain) UIImage * NEWSPIC; Store each News own image Object-(ID) initwithdictionary: (nsdictionary *) dic;//processing Resolution + (Nsmutablearray *) Handledata: (NSData *) data; @end #import "NewsItem.h" #import "ImageDownloader.h" @implementation newsitem-(void) Dealloc{self.newstitle = nil; Self.newspicurl = Nil;self.newspic = nil; [Super Dealloc];} -(ID) initwithdictionary: (nsdictionary *) dic{self = [Super Init];if (self) {self.newstitle = [dic objectforkey:@ "title"] ; self.newspicurl = [dic objectforkey:@ "Picurl"];//load image from local sandbox imagedownloader * downloader = [[[Imagedownloader Alloc] init] Autorelease];self.newspic = [Downloader loadlocalimage:_newspicurl];} return self;} + (Nsmutablearray *) Handledata: (NSData *) data; {//Parse data nserror * error = NIL; Nsdictionary * dic = [nsjsonserialization jsonobjectwithdata:data Options:nsjsonreadingmutaBlecontainers error:&error]; Nsmutablearray * Originalarray = [dic objectforkey:@ "News"];//encapsulate data Object Nsmutablearray * resultarray = [Nsmutablearray array ];for (int i=0; I<[originalarray count]; i++) {nsdictionary * newsdic = [Originalarray objectatindex:i]; NewsItem * item = [[NewsItem alloc] initwithdictionary:newsdic]; [Resultarray Addobject:item]; [item release];} return resultarray;} @end

@ Picture Download class #import <Foundation/Foundation.h> @class newsitem; @interface Imagedownloader:nsobject@property ( nonatomic,copy) NSString * IMAGEURL; @property (nonatomic,retain) NewsItem * NEWSITEM; Download the news that the image belongs to//after the image download is complete, use block implementation callback @property (nonatomic,copy) void (^completionhandler) (void);//Start download image-(void) Startdownloadimage: (NSString *) imageurl;//load image from local-(UIImage *) Loadlocalimage: (NSString *) imageUrl; @end #import " ImageDownloader.h "#import" NewsItem.h "@implementation imagedownloader-(void) Dealloc{self.imageurl = nil; Block_release (_completionhandler); [Super Dealloc];} #pragma mark-Asynchronous load-(void) Startdownloadimage: (NSString *) Imageurl{self.imageurl = imageurl;//First determine if the local sandbox already exists image, there is a direct fetch, There is no re-download, save after download//caches subfolder of the sandbox downloadimages in uiimage * image = [self loadlocalimage:imageurl];if (image = nil) {//Sandbox not There, download//asynchronous download, assign the concurrent queue Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{//multithreading, generated by default in the program process Download Image NSData * ImageData = [NSData datawithcontentsofurl:[nsurl urlwithString:imageurl]];            Cached images [ImageData writetofile:[self Imagefilepath:imageurl] atomically:yes]; Back to the main thread to complete the UI settings Dispatch_async (Dispatch_get_main_queue (), ^{//will download the image to be stored in NewsItem object UIImage * image = [UIImage Imagewithdata:imagedata];self.newsitem.newspic = image;//Use block to implement callback, notify image download complete if (_completionhandler) {_ Completionhandler ();}});});}    #pragma mark-Load local image-(UIImage *) Loadlocalimage: (NSString *) Imageurl{self.imageurl = IMAGEURL; Get Image Path NSString * FilePath = [self IMAGEFILEPATH:SELF.IMAGEURL]; UIImage * image = [UIImage imagewithcontentsoffile:filepath];if (image! = nil) {return image;} return nil;} #pragma mark-Get Image Path-(NSString *) Imagefilepath: (NSString *) imageurl{//get caches folder path NSString * Cachespath = [NSSEARCHPA Thfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject];//Create Downloadimages folder NSString * Downloadimagespath = [Cachespath stringbyappendingpathcomponent:@ "Downloadimages"]; Nsfilemanager * FileManager = [Nsfilemanager DefaultmanAger];if (![ FileManager Fileexistsatpath:downloadimagespath]) {[FileManager Createdirectoryatpath:downloadimagespath Withintermediatedirectories:yes Attributes:nil Error:nil];} #pragma mark stitching the path of the image file in the sandbox, because the image URL has "/", to be replaced before deposit, feel free to use "_" instead of NSString * imageName = [IMAGEURL stringbyreplacingoccurrencesofstring:@ "/" withstring:@ "_"]; NSString * Imagefilepath = [Downloadimagespath stringbyappendingpathcomponent:imagename];return imageFilePath;} @end

@ Here only the key code, network request, data processing, custom cell self-resolution #pragma mark-table View data source-(Nsinteger) Numberofsectionsintableview: (    UITableView *) tableview{//Return the number of sections. return 1;} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{//Return the number of rows    The section.    if (_dataarray.count = = 0) {return 10; } return [_dataarray count];} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{static NSString *cellidentifier = @ "Cell"; Newslistcell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier];if (!cell) {cell = [[Newslistcell Alloc] Initwithstyle:uitableviewcellstyledefault Reuseidentifier:cellidentifier] autorelease];} NewsItem * item = [_dataarray Objectatindex:indexpath.row];cell.titlelabel.text = item.newstitle;//Judging the news to be displayed there is no image if (                Item.newspic = = nil) {//no image download Cell.picImageView.image = nil; NSLog (@ "dragging =%d,decelerating =%d",self.tableview.dragging,self.tableview.decelerating); // ?? Timing and frequency of execution if (self.tableView.dragging = = no && self.tableView.decelerating = = no) {[Self Startpicdownload:item Forindexpath:indexpath];}}        else{//has an image directly showing NSLog (@ "1111"); cell.picImageView.image = Item.newspic;} Cell.titleLabel.text = [NSString stringwithformat:@ "indexpath.row =%ld", Indexpath.row];return Cell;} -(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath{return [Newslistcell Cellheight];} Start download image-(void) Startpicdownload: (NewsItem *) Item Forindexpath: (Nsindexpath *) indexpath{//Create image Downloader Imagedownloader * Downloader = [[Imagedownloader alloc] init];//downloader to download the image of which news, after the download is complete, the news save image Downloader.newsitem = item;//The callback function after the download is complete [ Downloader setcompletionhandler:^{//The callback part to be executed after the download is completed, the block's implementation//Gets the Cell object according to Indexpath and loads the image #pragma mark Cellforrowatindexpath--> didn't see Newslistcell. * Cell = (Newslistcell *) [Self.tableview Cellforrowatindexpath:indexpath ];cell.picimageview.image = Downloader.newsitem.newspic;}];/ /Start Download [Downloader STARTDOWNLOADIMAGE:ITEM.NEWSPICURL]; [Downloader release];} -(void) loadimagesforonscreenrows{#pragma mark Indexpathsforvisiblerows--> did not see//Get the cell TableView is displayed on the window, Load these cell images. The Cell object Nsarray * visiblecells = [Self.tableview indexpathsforvisiblerows];for (Nsindexpath *) that needs to be shown on this line can be obtained through Indexpath. Indexpath in Visiblecells) {NewsItem * item = [_dataarray objectatindex:indexpath.row];if (item.newspic = nil) {//If the news is not yet Download the image and start downloading [self Startpicdownload:item Forindexpath:indexpath];}} #pragma mark-Delay load key//tableview stop dragging, stop scrolling-(void) scrollviewdidenddragging: (Uiscrollview *) ScrollView willdecelerate     :(BOOL) decelerate{//if TableView stops scrolling, start loading the image if (!decelerate) {[Self loadimagesforonscreenrows];} NSLog (@ "%s__%d__|%d", __function__,__line__,decelerate);} -(void) scrollviewdidenddecelerating: (Uiscrollview *) scrollview{//start loading the image if TableView stops scrolling [self Loadimagesforonscreenrows];}



IOS---tableview optimized lazy (lazy loading) mode and asynchronous load mode when loading images

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.