一些前期準備
最終效果需求:界面使用storyboard搭建
plist文件定義:
數據模型:
#import "DataModel.h"
@implementation DataModel
+(instancetype)appInfoFromDic:(NSDictionary *)dic{
DataModel *appInfo = [[DataModel alloc] init];
[appInfo setValuesForKeysWithDictionary:dic];
return appInfo;
}
@end
自定義cell:
#import "HXCustomCell.h"
@implementation HXCustomCell
- (void)awakeFromNib {
// Initialization code
}
-(void)setAppInfo:(DataModel *)appInfo{
self.name.text = appInfo.name;
self.dowload.text = appInfo.download;
//設置占位圖片堕绩,這里直接在storyboard中設置好了
// self.icon.image = [UIImage imageNamed:@"user_default"];
}
@end
vc中用一個數組保存所有模型數據
/** 所有數據 */
@property (nonatomic, strong) NSArray *apps;
- (NSArray *)apps
{
if (!_apps) {
NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil]];
NSMutableArray *appArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
[appArray addObject:[DataModel appInfoFromDic:dict]];
}
_apps = appArray;
}
return _apps;
}
圖片加載
在cell生成的時候下載圖片,由于圖片下載是耗時操作凶朗,用同步方式去下載圖片的時候传透,系統無法很快執(zhí)行界面渲染浆西,導致“卡主線程”tableview滑動不流暢。因此圖片下載要放在子線程中執(zhí)行壁畸,下載后回到主線程顯示圖片。如下:
/** 隊列對象 */
@property (nonatomic, strong) NSOperationQueue *queue;
- (NSOperationQueue *)queue
{
if (!_queue) {
_queue = [[NSOperationQueue alloc] init];
_queue.maxConcurrentOperationCount = 3;//最大并發(fā)數
}
return _queue;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"app";
HXCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
DataModel *appModel = self.apps[indexPath.row];
cell.appInfo = appModel;
NSBlockOperation *downloadIMG = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"下載圖片%@",appModel.name);
// 下載圖片
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:appModel.icon]];
UIImage *image = [UIImage imageWithData:data];
// [NSThread sleepForTimeInterval:1.0];//模擬網絡延時
// 回到主線程顯示圖片
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
cell.icon.image = image;
}];
}];
[self.queue addOperation:downloadIMG];
return cell;
}
@end
如上蜗元,主線程不卡了,但有新的問題出現:頻繁滾動時系冗,圖片可能錯位(可以把上面模擬網絡延時的代碼取消注釋運行查看)奕扣,并且圖片來回跳,反復下載相同圖片(來回拖動tableview掌敬,從上面代碼的控制臺輸出看到“下載圖片xxx”多次打庸叨埂)
1.先說說反復下載圖片。由于cell復用引起奔害,因為每行單元格只要顯示出來就至少要調用一次cellForRow.....
方法來獲得它需要顯示的數據循帐。
解決辦法:內存緩存
圖片下載完就用一個字典緩存起來。每次調用到tableview代理方法時舀武,先從內存緩存中取圖片拄养,取不到再下載圖片然后存到數組中。
/** 內存緩存的圖片 */
@property (nonatomic, strong) NSMutableDictionary *images;
- (NSMutableDictionary *)images
{
if (!_images) {
_images = [NSMutableDictionary dictionary];
}
return _images;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"app";
HXCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
cell.icon.image = nil;
DataModel *appModel = self.apps[indexPath.row];
cell.appInfo = appModel;
UIImage *image = self.images[appModel.icon];
if (image) { // 內存中有圖片
NSLog(@"內存緩存%@",appModel.name);
cell.icon.image = image;
}else{
NSBlockOperation *downloadIMG = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"下載圖片%@",appModel.name);
// 下載圖片
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:appModel.icon]];
UIImage *image = [UIImage imageWithData:data];
[NSThread sleepForTimeInterval:1.0];//模擬網絡延時
// 回到主線程顯示圖片
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.images setObject:image forKey:appModel.icon];//把圖片放到數組緩存起來
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}];
}];
[self.queue addOperation:downloadIMG];
}
return cell;
}
然而银舱!這樣還是不能徹底解決多次下載圖片的問題瘪匿!想想如果滑動過快而網絡不佳等原因圖片加載延時,這時如果再滑動回去之前的cell寻馏,因為圖片還沒下載好棋弥,內存緩存數組里面是取不到數據的,這時還是會再次開啟下載诚欠。
解決辦法:操作緩存
每開啟了下載就把這個任務(operation對象)用一個字典緩存起來顽染,當下載完成了就把它移除。在內存緩存中取不到圖片后轰绵,去詢問是否有下載任務在進行粉寞,沒有下載任務再去下載。
//操作緩存
@property(nonatomic,strong) NSMutableDictionary *operationCache;
-(NSMutableDictionary *)operationCache{
if(!_operationCache){
_operationCache = [NSMutableDictionary dictionary];
}
return _operationCache;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"app";
HXCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
cell.icon.image = nil;
DataModel *appModel = self.apps[indexPath.row];
cell.appInfo = appModel;
UIImage *image = self.images[appModel.icon];
if (image) { // 內存中有圖片
NSLog(@"內存緩存%@",appModel.name);
cell.icon.image = image;
}else if (self.operationCache[appModel.icon]){
//已經在下載了左腔,只是還沒下載完
NSLog(@"圖片正在下載,請稍后%@",appModel.name);
}
else{
NSBlockOperation *downloadIMG = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"下載圖片%@",appModel.name);
// 下載圖片
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:appModel.icon]];
UIImage *image = [UIImage imageWithData:data];
[NSThread sleepForTimeInterval:1.0];//模擬網絡延時
// 回到主線程顯示圖片
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.operationCache removeObjectForKey:appModel.icon];//把下載操作移出緩存
// cell.icon.image = image;
[self.images setObject:image forKey:appModel.icon];//把圖片放到數組緩存起來
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}];
}];
[self.operationCache setObject:downloadIMG forKey:appModel.icon];//把還在進行的操作緩存起來
[self.queue addOperation:downloadIMG];
}
return cell;
}
2.圖片“錯位”唧垦。也是由于cell復用引起的,比如當網絡狀況不佳液样,下載圖片耗時比較長振亮,當圖片還沒下載完顯示到cell上。由于cell是重用的鞭莽,如果被重用的cell上有圖片數據坊秸,那么當前cell顯示的圖片就是被重用cell的圖片了。雖然這個當前cell也會下載當前行需要顯示的圖片澎怒,但直到圖片下載好了才會替換掉之前那張圖片褒搔。
解決辦法:在dequeue取得復用的cell后先把圖片清空(不管是否真的有內容)。
static NSString *ID = @"app";
HXCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
cell.icon.image = nil;
......
而且要注意的是,在主線程刷新圖片不要這樣寫cell.icon.image = image;
這樣還是會出現圖片錯位的站超。使用reloadRowsAtIndexPaths......
方法直接刷新某一行的數據,這個方法會觸發(fā)調用cellForRow......
方法
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// cell.icon.image = image;
[self.images setObject:image forKey:appModel.icon];//把圖片放到數組緩存起來
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}];
3.最后還有一個問題乖酬。當系統內存不足的時候死相,清除內存緩存,這個時候上下滾動又回去下載之前下載過的圖片咬像。又或者退出程序算撮,再次打開app時又重新下載圖片了。
解決辦法:用沙盒把數據保存下來
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"app";
HXCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
cell.icon.image = nil;
DataModel *appModel = self.apps[indexPath.row];
cell.appInfo = appModel;
// 先從內存緩存中取出圖片
UIImage *image = self.images[appModel.icon];
if (image) { // 內存中有圖片
NSLog(@"內存緩存%@",appModel.name);
cell.icon.image = image;
}else if (self.operationCache[appModel.icon]){
NSLog(@"圖片正在下載,請稍后%@",appModel.name);
}
else { // 內存中沒有圖片
// 獲得Library/Caches文件夾
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// 獲得文件名
NSString *filename = [appModel.icon lastPathComponent];
// 計算出文件的全路徑
NSString *file = [cachesPath stringByAppendingPathComponent:filename];
// 加載沙盒的文件數據
NSData *data = [NSData dataWithContentsOfFile:file];
// NSData *data = nil;
if (data) { // 直接利用沙盒中圖片
UIImage *image = [UIImage imageWithData:data];
cell.icon.image = image;
// 存到字典中
self.images[appModel.icon] = image;
} else { // 下載圖片 queue設置最大并發(fā)數
NSBlockOperation *downloadIMG = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"下載圖片%@",appModel.name);
// 下載圖片
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:appModel.icon]];
// if (data ==nil) {//如果圖片下載不成功
// [self.operationCache removeObjectForKey:appModel.icon];
// return ;
// }
UIImage *image = [UIImage imageWithData:data];
[NSThread sleepForTimeInterval:1.0];
// 回到主線程顯示圖片
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.operationCache removeObjectForKey:appModel.icon];//把下載操作移出緩存
// cell.icon.image = image;//不要這樣寫县昂,會圖片錯位
if (image == nil) {//如果圖片下載不成功
return ;
}
//圖片存到字典
[self.images setObject:image forKey:appModel.icon];
// 刷新tableviewcell
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}];
// 將圖片文件數據寫入沙盒中
[data writeToFile:file atomically:YES];
}];
[self.operationCache setObject:downloadIMG forKey:appModel.icon];//把還在進行的操作緩存起來
[self.queue addOperation:downloadIMG];
}
}
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
self.images = nil;
self.operationCache = nil;
//[self.queue cancelAllOperations];
}
ps:沙盒操作肮柜,這種讀寫文件的操作(IO操作)相對比較耗時,放到子線程去做倒彰,主線程用來渲染审洞。上面的代碼還沒把讀寫操作放子線程。
總結: