美文网首页
SDWebImage框架源码分析之SDImageCache

SDWebImage框架源码分析之SDImageCache

作者: _Vitality | 来源:发表于2017-12-13 09:09 被阅读0次
    SDWebImage-Cache.png

    SDImageCacheConfig配置文件

    SDImageCacheConfig和SDImageCache是聚合关系,SDImageCacheConfig为SDImageCache提供一些默认的属性配置:
    @property (assign, nonatomic) BOOL shouldDecompressImages;//默认是YES,自动解压图片,提高性能的同时产生了消耗大量内存的副作用。但是如果出现由于消耗大量内存导致程序崩溃的问题,可以关闭这一性能优化
    @property (assign, nonatomic) BOOL shouldDisableiCloud;//默认不在iClound中备份图片
    @property (assign, nonatomic) BOOL shouldCacheImagesInMemory;//默认在内存中缓存图片

    @property (assign, nonatomic) NSDataReadingOptions diskCacheReadingOptions;//设置这个枚举值可以提高磁盘缓存的性能
    @property (assign, nonatomic) NSInteger maxCacheAge;//磁盘缓存周期
    @property (assign, nonatomic) NSUInteger maxCacheSize;//磁盘缓存最大Size

    SDImageCache清理内存

    AutoPurgeCache

    在SDWebimage中含有一个自动清理缓存的类AutoPurgeCache,这个类继承于NSCache。
    在AutoPurgeCache中有一个构造方法

    - (id)init{
       self = [super init];
       if (self) {
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
       }
    return self;
    }

    这个构造方法在初始化时,注册了一个通知,当接受到内存警告的通知时,执行removeAllObjects 方法,这个方法其实来自于AutoPurgeCache类的父类NSCache

    NSCache

    NSCache类是iOS系统中原生的缓存类,这个类和NSDictionary类十分相似,可以通过键值对进行取值/赋值/移除操作
    - (nullable ObjectType)objectForKey:(KeyType)key;
    - (void)setObject:(ObjectType)obj forKey:(KeyType)key; // 0 cost
    - (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g;
    - (void)removeObjectForKey:(KeyType)key;
    - (void)removeAllObjects;
    这里我们需要注意的三个属性:
    @property NSUInteger totalCostLimit; //设置成本上限,图片的成本=image.width * image.height
    @property NSUInteger countLimit; //设置缓存数量上限
    @property BOOL evictsObjectsWithDiscardedContent;//自动移除上限,该布尔值标识缓存是否自动舍弃那些内存已经被丢弃的对象,如果设置为YES,则在对象的内存被丢弃时舍弃对象。默认值为YES

    SDImageCache清理磁盘缓存

    在SDImageCache中有两个处理磁盘缓存的方法:

    -(void)deleteOldFiles //清理磁盘
    - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion //清空磁盘

    - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion这个方法就是把把磁盘缓存的文件整个删除,简单粗暴,这里就不多介绍了,我会着重写一下-(void)deleteOldFiles方法。
    在初始化SDImageCache时,我们会注册三个通知:

    //清理内存
     [[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];
    

    其中第一个通知UIApplicationDidReceiveMemoryWarningNotification被响应时会执行clearMemory方法,这个方法其实也是调用了NSCache中的removeAllObjects方法,和AutoPurgeCache是一样的原理.

    当程序退出时,会接受到一个UIApplicationWillTerminateNotification的通知,此时会执行deleteOldFiles ()方法,这里是清理磁盘 的方法。

    在SDWebImage中deleteOldFiles ()是一个重要函数,接下来好好分析一下SDWebImage清除磁盘缓存的逻辑和思想:

    - (void)deleteOldFiles {
        [self deleteOldFilesWithCompletionBlock:nil];
    }
    - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock {
        dispatch_async(self.ioQueue, ^{
            // 磁盘缓存的路径
            NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
           /*  resourceKeys :期望获取文件的哪些属性
             NSURLIsDirectoryKey, 目录key
             NSURLContentModificationDateKey, url指向的内容,最后修改时间的key
             NSURLTotalFileAllocatedSizeKey 文件总大小的key
             */
            NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
    
            NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
                                                       includingPropertiesForKeys:resourceKeys
                                                                          options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                     errorHandler:NULL];
    
            // 过期时间,maxCacheAge默认是一周,单位是'秒'
            NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.config.maxCacheAge];
            // 采用字典存储缓存文件的路径
            NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *cacheFiles = [NSMutableDictionary dictionary];
            // 用来 标记计算当前缓存文件所占空间大小
            NSUInteger currentCacheSize = 0;
            // 记录需要删除的缓存文件路径
            NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init];
            // 遍历上述根据条件筛选出来的目录集合
            for (NSURL *fileURL in fileEnumerator) {
                NSError *error;
                // 根据 限定的文件信息resourceKeys获取文件内容
                NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];
    
                //  主要判断如果当前文件是目录,就跳过
                if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) {
                    continue;
                }
                //拿到最后修改时间
                NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
               // 判断文件是否过期,过期的话添加到预先准备的数值(存储需要删除文件的路径)中
                if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
                    [urlsToDelete addObject:fileURL];
                    continue;
                }
    
                /*1.累计计算未过期文件所在内存空间的大小
                  2.对未过期的文件采用键值对的方式存储起来,为后续二次清理磁盘缓存做准备
                 */
                NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
                currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
                cacheFiles[fileURL] = resourceValues;
            }
            // 删除过期文件
            for (NSURL *fileURL in urlsToDelete) {
                [_fileManager removeItemAtURL:fileURL error:nil];
            }
            // 如果在清除过期文件后,发现用户设置了磁盘缓存最大空间限制 并且当前缓存图片所在总空间大于用户期望的最大空间限制,对磁盘空间进行二次清理。
            if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
                // 预设一个合理缓存空间大小值,用来和后面清理磁盘缓存后的大小做比较。
                const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2;
    
               // 对缓存文件按照修改时间进行升序排列,时间最早的排在第一个
                NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
                                                                         usingComparator:^NSComparisonResult(id obj1, id obj2) {
                                                                             return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
                                                                         }];
                // 对缓存文件进行清理,直到缓存所占空间小于设置的期望值desiredCacheSize
                for (NSURL *fileURL in sortedFiles) {
                    if ([_fileManager removeItemAtURL:fileURL error:nil]) {
                        NSDictionary<NSString *, id> *resourceValues = cacheFiles[fileURL];
                        NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
                        currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;
    
                        if (currentCacheSize < desiredCacheSize) {
                            break;
                        }
                    }
                }
            }
            if (completionBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock();
                });
            }
        });
    }
    

    总结一下清理磁盘的步骤:

    • 删除过期文件
    • 计算剩余缓存文件的大小,如果依然超过预设置的最大缓存Size,将剩余文件按照最后修改时间进行升序,依次删除文件,直到剩余缓存文件所占空间小于 1/2 预设置的最大缓存空间。

    小知识补充:

    NS_ENUM和NS_OPTIONS的区别
    1. NSInteger(ENUM),OPTIONS(NSUInteger)
    2. 一个位移枚举, 一个是整型的
    3. 如果是options它可以是多个一起使用, enum只能一个单独进行使用
    4. 编译方式不一样,options C++ NSUInteger

    FOUNDATION_STATIC_INLINE

    static__inline__ 这表明方法是一个内联函数,static表示只在当前文件可见,避免在多个文件中使用相同的函数名导致的冲突问题。
    在程序中如果我们需要频繁的调用一个简单逻辑的方法,那么将它定义成一个内联函数的话,会提升调用效率。

    相关文章

      网友评论

          本文标题:SDWebImage框架源码分析之SDImageCache

          本文链接:https://www.haomeiwen.com/subject/xjtduxtx.html