本文基于V4.0.0 github.com/rs/SDWebIma…
脑图 naotu.baidu.com/file/c9eb5d…
Disk 缓存清理策略
总结:
SDWebImage 会在每次 APP 结束的时候执行清理任务。清理缓存的规则分两步进行:
第一步先清除掉过期的缓存文件。
如果清除掉过期的缓存之后,空间还不够。
那么就继续按文件时间从早到晚排序,先清除最早的缓存文件,直到剩余空间达到要求。
复制代码
@interface SDImageCacheConfig : NSObject
//文件缓存的时长
@property (assign, nonatomic) NSInteger maxCacheAge;
//控制 SDImageCache 所允许的最大缓存空间
@property (assign, nonatomic) NSUInteger maxCacheSize;
复制代码
1、maxCacheAge
maxCacheAge默认值
#import "SDImageCacheConfig.h"
static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week
复制代码
maxCacheAge是文件缓存的时长, SDWebImage 会注册两个通知:
//内存警告
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearMemory)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
//应用结束
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deleteOldFiles)
name:UIApplicationWillTerminateNotification
object:nil];
//应用进入后台
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(backgroundDeleteOldFiles)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
复制代码
分别在应用进入后台和结束的时候,遍历所有的缓存文件,如果缓存文件超过 maxCacheAge 中指定的时长,就会被删除掉。
- 是都执行此方法
- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock;
复制代码
2、maxCacheSize
源码里面并没有对maxCacheSize设置默认值,所以在默认情况下不会对缓存空间设置限制。
SDImageCache.m 534行
// If our remaining disk cache exceeds a configured maximum size, perform a second
// size-based cleanup pass. We delete the oldest files first.
if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
...
}
复制代码
上面代码中的 currentCacheSize 变量代表当前图片缓存占用的空间。 从这里可以看出,只有在 maxCacheSize 大于 0 并且当前缓存空间大于 maxCacheSize 的时候才进行第二步的缓存清理。
这也意味着SDWebImage 在默认情况下是不对我们的缓存大小设限制的,理论上,APP 中的图片缓存可以占满整个设备。
建议给APP设置一个合理的maxCacheSize
[SDImageCache sharedImageCache].maxCacheSize = 1024 * 1024 * 50; // 50M
复制代码