多線程實現多圖片下載1,多線程實現圖片下載
展示效果如下:
大家可以看到這個介面很簡單,其實就是UITableView的布局,
但是痛點是在於如何從網上下載這些圖片,下載之後應如何進行儲存!
我們一步一步進行解析,先從單線程(主線程)進行多圖片下載
我們布局上的文字及圖片的地址從plist檔案中進行讀取
根據結構,我們自訂一個資料模型檔案
DDZApp.h
#import <Foundation/Foundation.h>@interface DDZApp : NSObject//表徵圖@property (nonatomic,strong) NSString *icon;//名字@property (nonatomic,strong) NSString *name;//下載量@property (nonatomic,strong) NSString *download;+ (instancetype)appWithDict:(NSDictionary *)dict;@end
DDZApp.m
#import "DDZApp.h"@implementation DDZApp+ (instancetype)appWithDict:(NSDictionary *)dict { DDZApp *app = [[self alloc] init]; [app setValuesForKeysWithDictionary:dict]; return app;}@end
以下的都是視圖控制器中的代碼
ViewController.m
1.
@interface ViewController ()//所有資料@property (nonatomic,strong)NSArray *apps;//記憶體緩衝圖片@property (nonatomic,strong)NSMutableDictionary *imgCache;@end
第一個屬性用於儲存讀取plist檔案中的內容,設定為屬性儲存起來,就可以不用重複讀取
第二個屬性用於儲存從網上下載下來的圖片,也是為了不用重複讀取
2.
@implementation ViewController//讀取資料- (NSArray *)apps { if (!_apps) { //從plist檔案中讀取資料 NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil]]; NSMutableArray *appArray = [NSMutableArray array]; for (NSDictionary *dict in dictArray) { [appArray addObject:[DDZApp appWithDict:dict]]; } _apps = appArray; } return _apps;}//緩衝圖片- (NSMutableDictionary *)imgCache { if (!_imgCache) { //初始化 _imgCache = [NSMutableDictionary dictionary]; } return _imgCache;}
這兩個方法都是為了初始化剛才的兩個屬性
3.
#pragma mark - 資料來源方法- (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 dequeueReusableCellWithIdentifier:ID]; DDZApp *app = self.apps[indexPath.row]; cell.textLabel.text = app.name; cell.detailTextLabel.text = app.download; //先從記憶體中取出圖片 UIImage *image = self.imgCache[app.icon]; if (image) { cell.imageView.image = image; }else { //記憶體中沒有圖片 //將圖片檔案資料寫入到沙箱中 NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; //獲得檔案名稱 NSString *filename = [app.icon lastPathComponent]; //計算出檔案的全路徑 NSString *file = [cachesPath stringByAppendingPathComponent:filename]; //載入沙箱的檔案資料 NSData *data = [NSData dataWithContentsOfFile:file]; //判斷沙箱中是否有圖片 if (data) { //直接載入沙箱中圖片 cell.imageView.image = [UIImage imageWithData:data]; //存到字典(記憶體)中 self.imgCache[app.icon] = cell.imageView.image; }else { //下載圖片 data = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]]; cell.imageView.image = [UIImage imageWithData:data]; //存到記憶體中 self.imgCache[app.icon] = cell.imageView.image; //將圖片資料寫入到沙箱中 [data writeToFile:file atomically:YES]; } } return cell;}View Code
這兩個方法是UITableView必須要實現的方法
第一個是返回資料量,沒什麼好說的
第二個是綁定資料
具體的流程看