Winter's House.

SDWebImage项目中的应用

字数统计: 680阅读时长: 2 min
2019/03/12 Share

我们在面试中常被问到知名三方库的使用原理,我们经常认为这些原理对我们真正工作当时的帮助不大,但是随着项目不断迭代,对APP的性能及稳定提出越来越多的要求。我们逐渐会接触到通过三方库原理去思考使用三方库的策略来方便开发。这篇描述的是一个SDWebImage的使用案例。

安装与简单使用

安装

cocoaPods->Podfile

1
2
platform :ios, '7.0'
pod 'SDWebImage', '~> 4.0'

简单使用

引入头文件

1
#import <SDWebImage/UIImageView+WebCache.h>

加载网络图片

1
2
[imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

项目中使用

对于SDImageCache的应用

阅读源码我们发现SDImageCache类负责管理内存缓存和磁盘缓存,为了方便调用它提供了一个单例sharedImageCache,之前也都是一直使用这个方法,但是遇到这个需求后变化就来了。

情景

即时聊天,要求做图片缓存(类似微信),要求每个conversation以conversationId为文件夹名字,将当前conversation中的图片存入该文件夹中,并且在不使用一键清除缓存的情况下,图片一致保留。

SDImageCache方案

默认的路径

1
沙盒中的Cache

默认的缓存方案

1
2
3
4
先清除已超过最大缓存时间的缓存文件(最大缓存时间默认为一星期)
在第一轮清除的过程中保存文件属性,特别是缓存文件大小
在第一轮清除后,如果设置了最大缓存并且保留下来的磁盘缓存文件仍然超过了配置的最大缓存,那么进行第二轮以大小为基础的清除。
首先删除最老的文件,直到达到期望的总的缓存大小,即最大缓存的一半。

情景方案

路径

在SDImageCache的头文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

/**
* Returns global shared cache instance
*
* @return SDImageCache global instance
*/
+ (nonnull instancetype)sharedImageCache;

/**
* Init a new cache store with a specific namespace
*
* @param ns The namespace to use for this cache store
*/
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns;

/**
* Init a new cache store with a specific namespace and directory
*
* @param ns The namespace to use for this cache store
* @param directory Directory to cache disk images in
*/
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
diskCacheDirectory:(nonnull NSString *)directory NS_DESIGNATED_INITIALIZER;

使用这些来创建另外的命名空间

缓存方案

仿照SDImageCache的实现进行修改,删除缓存的时间及清除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Clear all memory cached images
*/
- (void)clearMemory;

/**
* Async clear all disk cached images. Non-blocking method - returns immediately.
* @param completion A block that should be executed after cache expiration completes (optional)
*/
- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion;

/**
* Async remove all expired cached image from disk. Non-blocking method - returns immediately.
* @param completionBlock A block that should be executed after cache expiration completes (optional)
*/
- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock;

CATALOG
  1. 1. 安装与简单使用
    1. 1.1. 安装
      1. 1.1.1. cocoaPods->Podfile
    2. 1.2. 简单使用
      1. 1.2.1. 引入头文件
      2. 1.2.2. 加载网络图片
  2. 2. 项目中使用
    1. 2.1. 对于SDImageCache的应用
      1. 2.1.1. 情景
        1. 2.1.1.1. SDImageCache方案
        2. 2.1.1.2. 情景方案
          1. 2.1.1.2.1. 路径
          2. 2.1.1.2.2. 缓存方案