SDWebImage 缓存机制(笔记)

本文基于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
复制代码
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值