圖片重復下載
若下載的圖片量較大,則會出現UI界面不流暢的現象
由于cell的循環利用造成的圖片顯示錯亂問題
subTitle類型的cell,無法顯示圖片
其核心代碼主要在tableView的返回創建cell的代理方法中,所以以下主要對該方法的實現進行解析
主要流程
設置模型類,包含以下屬性
/**圖片*/@PRoperty (nonatomic, strong) NSString *icon;/**名字*/@property (nonatomic, strong) NSString *name;/**下載量*/@property (nonatomic, strong) NSString *download;
需要用到的成員屬性
/**模型數組,用來存放每個cell的數據模型*/@property (nonatomic, strong) NSArray *apps;/**操作隊列,操作只有添加到隊列才有可能并發執行*/@property (nonatomic, strong) NSOperationQueue *queue;/**用于在內存中緩存圖片,部分避免圖片被多次下載*/@property (nonatomic, strong) NSMutableDictionary *imageCache;/**標記當前所有正在執行的操作,避免正在執行的操作被重復執行*/@property (nonatomic, strong) NSMutableDictionary *operations;
創建cell的方法的核心代碼
從內存緩存中取圖片
//內存中緩存的圖片在imagCache數組中self.imageCache[app.icon]
從沙盒中取圖片
//獲取文件路徑NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];//獲取文件名NSString *filename = [app.icon lastPathComponent];//計算出全路徑NSString *file = [cachePath stringByAppendingPathComponent:filename];//加載沙盒中的數據NSData *data = [NSData dataWithContentsOfFile:file];//判斷data中若有數據,否則從網絡上下載數據if (data){//沙盒中有數據 UIImage *image = [UIImage imageWithData:data]; cell.imageView.image = image; //存到字典中(即內存) self.imageCache[app.icon] = cell.imageView.image;}
從網絡上下載數據
//若subTitle類型的cell要顯示圖片,必須在第一次放回cell時就顯示圖片(或占位圖片)cell.imageView.image = [UIImage imageNamed:@"1"];//取得操作隊列中的操作NSOperation *operation = self.operations[app.icon];if (operation == nil){//不存在該圖片的下載操作 //創建下載圖片操作 operation = [NSBlockOperation blockOperationWithBlock:^{ //通過url加載數據 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]]; //數據加載失敗 if (data == nil) { //移除操作,以便刷新表格時能夠再次請求數據 [self.operations removeObjectForKey:app.icon]; return ; } //NSData轉換為UIImage UIImage *image = [UIImage imageWithData:data]; //存放到字典中 self.imageCache[app.icon] = image; //線程睡眠,模擬大數據下載 [NSThread sleepForTimeInterval:1]; //回主線程顯示圖片 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //通過indexPath刷新表格,此時內存緩存中已有圖片 [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; }]; //將圖片寫入沙盒 [data writeToFile:file atomically:YES]; //移除操作,保證在刷新表格時可以重新下載沒有下載的圖片 [self.operations removeObjectForKey:app.icon]; }]; //將操作添加到隊列 [self.queue addOperation:operation]; //保證圖片不被重復下載 self.operations[app.icon] = operation;
包含分類頭文件UIImageView+WebCache.h
圖片下載功能的實現
方法一
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder/** url:圖片的地址 placeholder:占位圖片*/
方法二
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock/** progressBlock:下載過程中的回調Block,可以在該Block中計算下載進度 completedBlock:下載完畢的回調方法*/
新聞熱點
疑難解答