IOS development practices-cell download image (NSOperation)

Source: Internet
Author: User

IOS development practices-cell download image (NSOperation)

The cell image in the scrolling list is downloaded and displayed from the server. The multi-thread and cache technologies are used to efficiently download and display images.

Cell Image download ideas:

1. Define the images dictionary to store the downloaded image (the image download url is used as the key and the image is used as the value). The cell image is first searched in the images dictionary. If not, go down (search in the sandbox ).

2. Check whether the sandbox exists. If so, set the cell image. Otherwise, the placeholder image (Enhancing the experience) is displayed and the thread is enabled to download the image.

3. Define the dictionary operations to store all download operations (the url is key and the operation object is value ). Determines whether the download operation exists. If yes, the download is in progress. Otherwise, the download operation is created.

4. After the download is complete, update the main thread: add the image to the images dictionary where the image is stored and remove the operation from the operations Dictionary (to prevent increasing operations and ensure that the download fails, can be downloaded again), save the image to the sandbox, and refresh the table.

 

Case: cell

1. Application Model

App. h

 

# Import
 
  
@ Interface App: NSObject // Application name @ property (nonatomic, copy) NSString * name; // downloads @ property (nonatomic, copy) NSString * download; // icon address @ property (nonatomic, copy) NSString * icon; + (instancetype) appWithDict :( NSDictionary *) dict; @ end
 
App. m
#import "App.h"@implementation App+(instancetype)appWithDict:(NSDictionary *)dict{    App *app = [[App alloc]init];    [app setValuesForKeysWithDictionary:dict];    return app;}@end
2. Define queues, store operation dictionaries, store image dictionaries, and apply app variables.
// App @ property (nonatomic, strong) NSMutableArray * apps; // queue for storing all downloaded images @ property (nonatomic, strong) NSOperationQueue * queue; // store all download operations (the url is key and the operation object is value) @ property (nonatomic, strong) NSMutableDictionary * operations; // store all downloaded images @ property (nonatomic, strong) NSMutableDictionary * images; # pragma lazy loading-(NSMutableArray *) apps {if (_ apps = nil) {NSMutableArray * appArr = [NSMutableArray array]; // retrieves the plist File NSString * file = [[NSBundle mainBundle] pathForResource: @ "apps" ofType: @ "plist"]; NSArray * dictArr = [NSArray arrayWithContentsOfFile: file]; // dictionary conversion model for (NSDictionary * dict in dictArr) {App * app = [App appWithDict: dict]; [appArr addObject: app];} _ apps = appArr ;} return _ apps;}-(NSOperationQueue *) queue {if (! _ Queue) {self. queue = [[NSOperationQueue alloc] init];} return _ queue;}-(NSMutableDictionary *) operations {if (! _ Operations) {self. operations = [[NSMutableDictionary alloc] init];} return _ operations;}-(NSMutableDictionary *) images {if (_ images) {self. images = [[NSMutableDictionary alloc] init];} return _ images ;}

3. Set cell and download images by thread

# 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 NSString * ID = @ "app"; UITableViewCell * cell = [tableView d EqueueReusableCellWithIdentifier: ID]; if (! Cell) {cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier: ID];} // retrieve the model App * app = self. apps [indexPath. row]; // set the cell. textLabel. text = app. name; cell. detailTextLabel. text = app. download; // obtain the UIImage * image = self from the images cache. images [app. icon]; if (image) {// indicates that the image has been downloaded (cached successfully) cell. imageView. image = image;} else {// indicates that the image has not been downloaded (not cached) // obtain the caches path, and splice the file path NSString * file = [[NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: [app. icon lastPathComponent]; // retrieve the image NSData * data = [NSData dataWithContentsOfFile: file] From the sandbox first; if (data) {// The cell file exists in the sandbox. imageView. image = [UIImage imageWithData: data];} else {// This file does not exist in the sandbox // display the placeholder image cell. imageView. image = [UIImage imageNamed: @ "placeholder"]; // download the image [self download: app. icon indexPath: indexPath] ;}} return cell;}-(void) download :( NSString *) imageUrl indexPath :( NSIndexPath *) indexPath {// retrieve the download operation (operations object) NSBlockOperation * operation = self corresponding to the current image url. operations [imageUrl]; if (operation) return; _ weak typeof (self) handle Vc = self; operation = [NSBlockOperation blockOperationWithBlock: ^ {NSURL * url = [NSURL URLWithString: imageUrl]; NSData * data = [NSData dataWithContentsOfURL: url]; // download image UIImage * image = [UIImage imageWithData: data]; // convert to image // return to the living thread [[NSOperationQueue mainQueue] addOperationWithBlock: ^ {if (image) {// store it in the dictionary ‑vc. images [imageUrl] = image; // Save the image to the sandbox for resolution) // UIImage --> NSData --> File (File) NSData * data = UIImagePNGRepresentation (image ); NSString * file = [callback (NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: [imageUrl lastPathComponent]; NSLog (@ "% @", file); [data writeToFile: file atomically: YES];} // remove the download operation from the dictionary (to prevent operations from getting bigger and bigger, and ensure that the download can be downloaded again after the download fails) [unzip VC. operations removeObjectForKey: imageUrl]; // refresh the table [invalid VC. tableView reloadRowsAtIndexPaths: @ [indexPath] withRowAnimation: UITableViewRowAnimationNone] ;}]; // Add the operation to the queue [self. queue addOperation: operation]; // Add it to the dictionary (this code is used to solve repeated downloads) self. operations [imageUrl] = operation ;}


 

4. Stop table downloading and start table downloading.

 

/*** Called when the user starts to drag a table */-(void) scrollViewWillBeginDecelerating :( UIScrollView *) scrollView {// pause the download [self. queue setsuincluded: YES];}/*** call/-(void) scrollViewDidEndDragging when you stop dragging a table: (UIScrollView *) scrollView willDecelerate :( BOOL) decelerate {// resume download [self. queue setsuincluded: NO];}

5. Memory warning: Remove all cache dictionaries.

 

 

-(Void) didReceiveMemoryWarning {[super didreceivemorywarning]; // remove all download operation caches [self. queue cancelAllOperations]; [self. operations removeAllObjects]; // remove all image caches [self. images removeAllObjects];}

Effect:

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.