標籤:
1 iOS多圖片下載、在cell裡面下載圖片、做了緩衝最佳化。 2 3 (app.icon是圖片地址) 4 5 // 先從記憶體緩衝中取出圖片 6 UIImage *image = self.images[app.icon]; 7 if (image) { // 記憶體中有圖片 8 cell.imageView.image = image; 9 } else { // 記憶體中沒有圖片10 // 獲得Library/Caches檔案夾11 NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];12 // 獲得檔案名稱13 NSString *filename = [app.icon lastPathComponent];14 // 計算出檔案的全路徑15 NSString *file = [cachesPath stringByAppendingPathComponent:filename];16 // 載入沙箱的檔案資料17 NSData *data = [NSData dataWithContentsOfFile:file];18 19 if (data) { // 直接利用沙箱中圖片20 UIImage *image = [UIImage imageWithData:data];21 cell.imageView.image = image;22 // 存到字典中23 self.images[app.icon] = image;24 } else { // 下載圖片25 [self.queue addOperationWithBlock:^{26 // 下載圖片、多線程27 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]];28 UIImage *image = [UIImage imageWithData:data];29 30 [NSThread sleepForTimeInterval:1.0];31 32 // 回到主線程顯示圖片33 [[NSOperationQueue mainQueue] addOperationWithBlock:^{34 cell.imageView.image = image;35 }];36 37 // 存到字典中38 self.images[app.icon] = image;39 // 將圖片檔案資料寫入沙箱中40 [data writeToFile:file atomically:YES];41 }];42 }
iOS多圖片下載