美文网首页收藏ios
SDWebImage缓存部分实现源码解析

SDWebImage缓存部分实现源码解析

作者: 某某香肠 | 来源:发表于2018-12-04 21:06 被阅读179次

    SDWebImage主要使用SDImageCache来缓存图片,实现了内存存取和磁盘存取还有一系列的处理。下面分析它的源码。本文分析的版本为4.4.3。首先来看一下它对开发者暴露的接口。

    属性

    首先我们来看一下它的属性

    #pragma mark - Properties
    //配置
    @property (nonatomic, nonnull, readonly) SDImageCacheConfig *config;
    //最大内存大小
    @property (assign, nonatomic) NSUInteger maxMemoryCost;
    //最大内存数量
    @property (assign, nonatomic) NSUInteger maxMemoryCountLimit;
    

    这3个属性都是可配置的属性,其中maxMemoryCost和maxMemoryCountLimit用于配置其内部的NSCache,config则负责大部分的配置,下面是它内部的属性。

    @interface SDImageCacheConfig : NSObject
    //是否解压缩图片,默认为YES
    @property (assign, nonatomic) BOOL shouldDecompressImages;
    //是否禁用iCloud备份,默认为YES
    @property (assign, nonatomic) BOOL shouldDisableiCloud;
    //是否缓存一份到内存中,默认为YES
    @property (assign, nonatomic) BOOL shouldCacheImagesInMemory;
    //是否额外存一份弱引用的缓存,默认为YES
    @property (assign, nonatomic) BOOL shouldUseWeakMemoryCache;
    //从磁盘读取图片的配置项,默认是NSDataReadingMappedIfSafe,也就是使用文件映射内存的方式,是不消耗内存的
    @property (assign, nonatomic) NSDataReadingOptions diskCacheReadingOptions;
    //写文件的配置项,默认是NSDataWritingAtomic,也就是会覆盖原有的文件
    @property (assign, nonatomic) NSDataWritingOptions diskCacheWritingOptions;
    //图片在磁盘的最大时间,默认是一周
    @property (assign, nonatomic) NSInteger maxCacheAge;
    //图片在磁盘的最大大小,默认是0,即没有限制
    @property (assign, nonatomic) NSUInteger maxCacheSize;
    //清除磁盘缓存是基于什么清除,默认是SDImageCacheConfigExpireTypeModificationDate,即基于图片修改时间
    @property (assign, nonatomic) SDImageCacheConfigExpireType diskCacheExpireType;
    @end
    

    可以看出SDImageCacheConfig中大多数配置都是跟磁盘相关的。

    初始化方法

    //单例
    + (nonnull instancetype)sharedImageCache;
    //新建一个存储类,如果是用init方法创建,默认传入的是default
    - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns;
    //全能初始化方法,比起上一个方法,额外指定了存储目录,默认目录是在Cache/default的文件夹下
    - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
                           diskCacheDirectory:(nonnull NSString *)directory NS_DESIGNATED_INITIALIZER;
    

    其全能初始化方法的实现如下:

    - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
                           diskCacheDirectory:(nonnull NSString *)directory {
        if ((self = [super init])) {
            NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
            //创建专门读写磁盘的队列,注意是并发
            _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
            //初始化配置config
            _config = [[SDImageCacheConfig alloc] init];
            //初始化内存空间
            _memCache = [[SDMemoryCache alloc] initWithConfig:_config];
            _memCache.name = fullNamespace;
            //初始化存储目录
            if (directory != nil) {
                _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
            } else {
                NSString *path = [self makeDiskCachePath:ns];
                _diskCachePath = path;
            }
            dispatch_sync(_ioQueue, ^{
                self.fileManager = [NSFileManager new];
            });
            //注册通知,大意就是在程序进后台和退出的时候,清理一下磁盘
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(deleteOldFiles)
                                                         name:UIApplicationWillTerminateNotification
                                                       object:nil];
    
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(backgroundDeleteOldFiles)
                                                         name:UIApplicationDidEnterBackgroundNotification
                                                       object:nil];
        }
        return self;
    }
    

    其中,makeDiskCachePath也是个暴露的方法:

    - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace {
        NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        return [paths[0] stringByAppendingPathComponent:fullNamespace];
    }
    

    显然文件的目录基本都在Cache目录下。

    内存存储设计

    这个类是使用SDMemoryCache来进行存储,它继承自NSCache,而在这个类中,又持有了一个weakCache属性弱引用着内存,它实际上是在config中的shouldUseWeakMemoryCache置为YES才有效的。

    @interface SDMemoryCache <KeyType, ObjectType> : NSCache <KeyType, ObjectType>
    @end
    @interface SDMemoryCache <KeyType, ObjectType> ()
    //配置
    @property (nonatomic, strong, nonnull) SDImageCacheConfig *config;
    //弱引用缓存
    @property (nonatomic, strong, nonnull) NSMapTable<KeyType, ObjectType> *weakCache; 
    //信号量的锁
    @property (nonatomic, strong, nonnull) dispatch_semaphore_t weakCacheLock; 
    - (instancetype)initWithConfig:(nonnull SDImageCacheConfig *)config;
    @end
    

    首先里面的NSMapTable相当于一个字典,他的相关知识可以参看这篇文章,总的来说,它可以设置键和值是赋值方式,当设置键的赋值方式为Copy,值的赋值方式为Strong的时候,它就相当于NSMutableDictionary。

    它自身也是一个NSCache,但与父类不一样的是,它多了一个收到内存警告,删除父类所有对象的功能。

    - (void)dealloc {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    
    - (instancetype)initWithConfig:(SDImageCacheConfig *)config {
        self = [super init];
        if (self) {
            //weakCache是一个键是强引用,值是弱引用的MapTable
            self.weakCache = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
            self.weakCacheLock = dispatch_semaphore_create(1);
            self.config = config;
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(didReceiveMemoryWarning:)
                                                         name:UIApplicationDidReceiveMemoryWarningNotification
                                                       object:nil];
        }
        return self;
    }
    
    - (void)didReceiveMemoryWarning:(NSNotification *)notification {
        //移除父类的对象
        [super removeAllObjects];
    }
    

    可以看出,在收到内存警告的时候,仅仅清除了父类的对象,并没有清除weakCache的对象,因为是弱引用类型,也不用手动清除。

    接下来就是一些操作内存的时候对weakCache的一些同步操作方法:

    //setObject的相关方法都会调到这里来,因此只需重写这个方法
    - (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g {
        [super setObject:obj forKey:key cost:g];
        if (!self.config.shouldUseWeakMemoryCache) {
            return;
        }
        if (key && obj) {
            LOCK(self.weakCacheLock);
            [self.weakCache setObject:obj forKey:key];
            UNLOCK(self.weakCacheLock);
        }
    }
    
    - (id)objectForKey:(id)key {
        //先看看自身有没有这个值
        id obj = [super objectForKey:key];
        if (!self.config.shouldUseWeakMemoryCache) {
            return obj;
        }
        if (key && !obj) {
            //从缓存找,找到的话重新设置回去
            LOCK(self.weakCacheLock);
            obj = [self.weakCache objectForKey:key];
            UNLOCK(self.weakCacheLock);
            if (obj) {
                NSUInteger cost = 0;
                if ([obj isKindOfClass:[UIImage class]]) {
                    cost = SDCacheCostForImage(obj);
                }
                [super setObject:obj forKey:key cost:cost];
            }
        }
        return obj;
    }
    //移除的时候,weakCache也需要同步移除
    - (void)removeObjectForKey:(id)key {    
        [super removeObjectForKey:key];
        if (!self.config.shouldUseWeakMemoryCache) {
            return;
        }
        if (key) {
            LOCK(self.weakCacheLock);
            [self.weakCache removeObjectForKey:key];
            UNLOCK(self.weakCacheLock);
        }
    }
    
    - (void)removeAllObjects {
        [super removeAllObjects];
        if (!self.config.shouldUseWeakMemoryCache) {
            return;
        }
        LOCK(self.weakCacheLock);
        [self.weakCache removeAllObjects];
        UNLOCK(self.weakCacheLock);
    }
    

    这一块代码容易读懂,主要思想是在NSCache因为某些原因清除的时候在内存中仍然维持着一份弱引用,只要这些弱引用的对象仍然被其他对象(比如UIImageView)所持有,那仍然会在该类中找到。

    虽然这里引入了SDImageCacheConfig,但是实际上只使用了它的shouldUseWeakMemoryCache属性,虽然代码看上去并没有直接设置shouldUseWeakMemoryCache这个成员属性来得好,但是以后扩展起来会容易一些。

    存储图片方法

    这个文件暴露了很多存图片的API,大部分都会调到下面的方法中来:

    - (void)storeImage:(nullable UIImage *)image
             imageData:(nullable NSData *)imageData
                forKey:(nullable NSString *)key
                toDisk:(BOOL)toDisk
            completion:(nullable SDWebImageNoParamsBlock)completionBlock {
            //没有图片和存储键直接返回
        if (!image || !key) {
            if (completionBlock) {
                completionBlock();
            }
            return;
        }
        //内存存一份
        if (self.config.shouldCacheImagesInMemory) {
            NSUInteger cost = SDCacheCostForImage(image);
            [self.memCache setObject:image forKey:key cost:cost];
        }
        
        if (toDisk) {
            dispatch_async(self.ioQueue, ^{
                    //这里的data比较大,存到磁盘后需要及时释放掉,不能让其继续占用内存
                @autoreleasepool {
                    NSData *data = imageData;
                    if (!data && image) {
                        //如果data为nil,则转换为data存储
                        SDImageFormat format;
                        if (SDCGImageRefContainsAlpha(image.CGImage)) {
                            format = SDImageFormatPNG;
                        } else {
                            format = SDImageFormatJPEG;
                        }
                        data = [[SDWebImageCodersManager sharedInstance] encodedDataWithImage:image format:format];
                    }
                    //磁盘存一份,这个方法会阻塞线程
                    [self _storeImageDataToDisk:data forKey:key];
                }
                if (completionBlock) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completionBlock();
                    });
                }
            });
        } else {
            if (completionBlock) {
                completionBlock();
            }
        }
    }
    
    - (void)_storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key {
        if (!imageData || !key) {
            return;
        }
        if (![self.fileManager fileExistsAtPath:_diskCachePath]) {
            [self.fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
        }
        //返回MD5后的字符串,这一步也是耗时的
        NSString *cachePathForKey = [self defaultCachePathForKey:key];
        NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
        //写文件
        [imageData writeToURL:fileURL options:self.config.diskCacheWritingOptions error:nil];
        if (self.config.shouldDisableiCloud) {
            //不让该文件被iCloud备份
            [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
        }
    }
    
    

    所有关于磁盘的耗时操作都放在ioQueue里操作,这样保证了主线程的正常运行。

    获取图片方法

    读取图片的方法有很多,其中先从最常用的方法讲起:

    - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key {
        //先从缓存读
        UIImage *image = [self imageFromMemoryCacheForKey:key];
        if (image) {
            return image;
        }
        //缓存找不到,就从磁盘找
        image = [self imageFromDiskCacheForKey:key];
        return image;
    }
    

    其中,imageFromMemoryCacheForKey这个方法比较简单,无非就是从memCache中读取而已,这里就不贴代码了。

    imageFromDiskCacheForKey这个方法的实现如下:

    - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key {
        UIImage *diskImage = [self diskImageForKey:key];
        if (diskImage && self.config.shouldCacheImagesInMemory) {
            //重新将图片放进内存
            NSUInteger cost = SDCacheCostForImage(diskImage);
            [self.memCache setObject:diskImage forKey:key cost:cost];
        }
        return diskImage;
    }
    
    - (nullable UIImage *)diskImageForKey:(nullable NSString *)key {
        //先读取出数据
        NSData *data = [self diskImageDataForKey:key];
        //再将数据转成图片
        return [self diskImageForKey:key data:data];
    }
    
    

    从磁盘中读取图片主要分成2个步骤,一是从磁盘中读取出数据,二是将数据转化为图片。

    - (nullable NSData *)diskImageDataForKey:(nullable NSString *)key {
        if (!key) {
            return nil;
        }
        __block NSData *imageData = nil;
        //在ioQueue,阻塞当前线程
        dispatch_sync(self.ioQueue, ^{
            imageData = [self diskImageDataBySearchingAllPathsForKey:key];
        });
        return imageData;
    }
    
    - (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key {
        //MD5字符串
        NSString *defaultPath = [self defaultCachePathForKey:key];
        NSData *data = [NSData dataWithContentsOfFile:defaultPath options:self.config.diskCacheReadingOptions error:nil];
        if (data) {
            return data;
        }
        //现在默认路径上找
        data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil];
        if (data) {
            return data;
        }
        //如果默认路径没找到,则在其他路径找,这些路径可由开发者配置
        NSArray<NSString *> *customPaths = [self.customPaths copy];
        for (NSString *path in customPaths) {
            NSString *filePath = [self cachePathForKey:key inPath:path];
            NSData *imageData = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil];
            if (imageData) {
                return imageData;
            }
            imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil];
            if (imageData) {
                return imageData;
            }
        }
        return nil;
    }
    
    - (nullable UIImage *)diskImageForKey:(nullable NSString *)key data:(nullable NSData *)data {
        return [self diskImageForKey:key data:data options:0];
    }
    
    - (nullable UIImage *)diskImageForKey:(nullable NSString *)key data:(nullable NSData *)data options:(SDImageCacheOptions)options {
        if (data) {
            //图片解码
            UIImage *image = [[SDWebImageCodersManager sharedInstance] decodedImageWithData:data];
            //这里主要是进行图片放大、动图的操作
            image = [self scaledImageForKey:key image:image];
            if (self.config.shouldDecompressImages) {
                BOOL shouldScaleDown = options & SDImageCacheScaleDownLargeImages;
                //解压图片
                image = [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&data options:@{SDWebImageCoderScaleDownLargeImagesKey: @(shouldScaleDown)}];
            }
            return image;
        } else {
            return nil;
        }
    }
    

    除了同步获取图片的方法,该类还提供了异步获取图片的方法,其原理基本是一样的,这里仅贴出接口:

    - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDCacheQueryCompletedBlock)doneBlock;
    

    他返回了一个NSOperation,开发者可以通过这个Operation中断查找。

    删除图片方法

    删除图片的实现如下:

    - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion {
        [self removeImageForKey:key fromDisk:YES withCompletion:completion];
    }
    
    - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion {
        if (key == nil) {
            return;
        }
        //从缓存删除
        if (self.config.shouldCacheImagesInMemory) {
            [self.memCache removeObjectForKey:key];
        }
    
        if (fromDisk) {
            //在ioQueue中从磁盘中删除
            dispatch_async(self.ioQueue, ^{
                [self.fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
                if (completion) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completion();
                    });
                }
            });
        } else if (completion){
            completion();
        }
        
    }
    

    可以看出,删除图片的操作还是比较简单的。

    此外,还有清除内存、清除磁盘的方法,代码也比较简单,这里就不贴出来了。

    删除磁盘旧图片功能实现

    SDImageCache还可以定期删除磁盘中的图片,其实现方式是在程序进入后台或者程序结束时,调用下面这个方法:

    - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock {
        dispatch_async(self.ioQueue, ^{
            NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
                //选择是根据修改时间还是根据创建时间清除老文件
            NSURLResourceKey cacheContentDateKey = NSURLContentModificationDateKey;
            switch (self.config.diskCacheExpireType) {
                case SDImageCacheConfigExpireTypeAccessDate:
                    cacheContentDateKey = NSURLContentAccessDateKey;
                    break;
    
                case SDImageCacheConfigExpireTypeModificationDate:
                    cacheContentDateKey = NSURLContentModificationDateKey;
                    break;
    
                default:
                    break;
            }
            //清除文件,只需要知道文件是否是文件夹、时间以及占用大小3个信息
            NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, cacheContentDateKey, NSURLTotalFileAllocatedSizeKey];
            //获取文件的迭代
            NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL
                                                       includingPropertiesForKeys:resourceKeys
                                                                          options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                     errorHandler:NULL];
            //得到过期的时间
            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;
                NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];
                //排除错误的文件以及文件夹
                if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) {
                    continue;
                }
                 //如果文件过期,则添加到待删除的数组中
                NSDate *modifiedDate = resourceValues[cacheContentDateKey];
                if ([[modifiedDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
                    [urlsToDelete addObject:fileURL];
                    continue;
                }
                //如果没有过期,则计算其占用大小
                NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
                currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
                cacheFiles[fileURL] = resourceValues;
            }
            
            for (NSURL *fileURL in urlsToDelete) {
                [self.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[cacheContentDateKey] compare:obj2[cacheContentDateKey]];
                                                                         }];
                for (NSURL *fileURL in sortedFiles) {
                    if ([self.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();
                });
            }
        });
    }
    

    总结

    总的来说,缓存的逻辑主要复杂在磁盘的读写上,所有的磁盘操作都放在io线程上读取。此外,在内存上使用NSCache+NSMapTable而不是NSDictionary存储图片,也值得我们借鉴。

    相关文章

      网友评论

        本文标题:SDWebImage缓存部分实现源码解析

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