TableView 多圖片下載(多線程)緩存問題

一些前期準備

最終效果需求:界面使用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生成的時候下載圖片,由于圖片下載是耗時操作,用同步方式去下載圖片的時候,系統無法很快執行界面渲染,導致“卡主線程”tableview滑動不流暢。因此圖片下載要放在子線程中執行,下載后回到主線程顯示圖片。如下:

/** 隊列對象 */
@property (nonatomic, strong) NSOperationQueue *queue;
- (NSOperationQueue *)queue
{
    if (!_queue) {
        _queue = [[NSOperationQueue alloc] init];
        _queue.maxConcurrentOperationCount = 3;//最大并發數
    }
    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......方法直接刷新某一行的數據,這個方法會觸發調用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設置最大并發數
            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操作)相對比較耗時,放到子線程去做,主線程用來渲染。上面的代碼還沒把讀寫操作放子線程。

總結:


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,180評論 4 61
  • *面試心聲:其實這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個offer,總結起來就是把...
    Dove_iOS閱讀 27,199評論 30 471
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,817評論 25 708
  • 今天跟公司一妹紙聊天,我:為什么女人都想要個二胎?有個二胎男人該多累呀!妹紙瞥了我一眼說道:生二胎你嫌累,要你娶二...
    小悠段子閱讀 847評論 0 2
  • 遼 489萬-1111年 遼朝全盛時期疆域東到日本海,西至阿爾泰山,北到額爾古納河、大興安嶺一帶,南到河北南部的白...
    趙果果果閱讀 391評論 0 0