圖片快取

weixin_33727510發表於2016-03-18

方案一:無沙盒

  1. 從快取取圖,並顯示
  2. 如快取無圖,則下載
  3. 下載完後,存入快取,並顯示

方案二:有沙盒

  1. 從快取取圖,並顯示
  2. 如快取無圖,從沙盒取圖、顯示,並存入快取
  3. 如沙盒無圖,則下載
  4. 下載完後,先存入快取、顯示,再存入沙盒

具體實現

/**
  self.apps = @[app1, app2, app3, ...];
  app1 = @{@"name":@"...", @"icon":@"http://p16.qhimg.com/dr/34_5/fo2489234n34k545l234.png", @"download":@"..."};
**/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   ... ...
   JKYApp *app = self.apps[indexPath.row];
   /**1 先從記憶體快取中取出圖片 **/
   UIImage *image = self.imageCache[app.icon];
   if (image) { /**2 快取有,則載入 **/
       cell.imageView.image = image;
   } else {  /**3 快取無,則下載 **/
       NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]];
       cell.imageView.image = [UIImage imageWithData:data];
       /**4 存到字典中 **/
       self.imageCache[app.icon] = cell.imageView.image;
       /**5 存到沙盒中 **/
       //5.1 獲取沙盒Library/Caches路徑
       NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCacheDirectory, NSUserDomainMask, YES) firstObject];
       //5.2 獲取檔名
       NSString *fileName = [app.icon lastPathComponent];
       //5.3 合併為檔案全路徑
       NSString *file = [caches stringByAppendingPathComponent:fileName];
       //5.4 第二個引數YES(原子性):當檔案未寫完出錯了,則該檔案不會殘留
       //          NO(費原子性):當檔案未寫完出錯了,則該檔案會殘留在沙盒
       //5.5 存到沙盒中
       [data writeToFile:file atomically:YES];
   }
}
/*說明:
   沙盒檔案結構:
     1. Documents:手機連到itunes後,會自動備份到蘋果伺服器。注:蘋果不允許下載的大檔案放在這裡,否則,應用將可能被拒絕通過稽核。
     2. Library
       - Caches:存放下載的檔案
       - Preference:偏好設定
     3. tmp:臨時
*/

相關文章