美文网首页
SDWebImage源码阅读(六)

SDWebImage源码阅读(六)

作者: 落叶兮兮 | 来源:发表于2020-07-09 14:54 被阅读0次

    在上一篇[SDWebImage源码阅读(五)](jianshu.com/p/fec6c0b8ed1b)中介绍了SDImageCahe.h文件,包括SDImageCacheConfig文件的阅读,这次开始阅读SDImageCache.m文件中的代码,了解实现思路。

    在最初的定义中,定义了开锁和解锁,这个代码值得学习以下

    #define LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
    #define UNLOCK(lock) dispatch_semaphore_signal(lock);
    

    之后定义了一个类SDMemoryCache,继承自NSCache,
    在初始化方法中,在缓存中,可能存在内存不足的情况,所以在init中注册了通知

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(didReceiveMemoryWarning:)
                                                         name:UIApplicationDidReceiveMemoryWarningNotification
                                                       object:nil];
    
    - (void)didReceiveMemoryWarning:(NSNotification *)notification {
       //只删除缓存,但是保持弱缓存
         [super removeAllObjects];
    }
    

    另外,在objectForKey:(id)key中有获取内存的花费的代码

    - (id)objectForKey:(id)key {
        id obj = [super objectForKey:key];
        if (!self.config.shouldUseWeakMemoryCache) {
            return obj;
        }
        if (key && !obj) {
            // Check weak cache
            LOCK(self.weakCacheLock);
            obj = [self.weakCache objectForKey:key];
            UNLOCK(self.weakCacheLock);
            if (obj) {
                // Sync cache
                NSUInteger cost = 0;
                if ([obj isKindOfClass:[UIImage class]]) {
                    //获取内存的花费
                    cost = [(UIImage *)obj sd_memoryCost];
                }
                [super setObject:obj forKey:key cost:cost];
            }
        }
        return obj;
    }
    

    点击跳转后,发现具体的计算内存花费的代码为:

    FOUNDATION_STATIC_INLINE NSUInteger SDMemoryCacheCostForImage(UIImage *image) {
    #if SD_MAC
        return image.size.height * image.size.width;
    #elif SD_UIKIT || SD_WATCH
        NSUInteger imageSize = image.size.height * image.size.width * image.scale * image.scale;
        return image.images ? (imageSize * image.images.count) : imageSize;
    #endif
    }
    

    接下来看SDImageCache.m中的代码
    获取磁盘存储路径的代码

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

    之后看到初始化的方法

    - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
                           diskCacheDirectory:(nonnull NSString *)directory {
    //创建io串行队列(名字由自己命名)
    _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
    ...
    //初始化磁盘缓存
    if (directory != nil) {
                _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
            } else {
                NSString *path = [self makeDiskCachePath:ns];
                _diskCachePath = path;
            }
    
            dispatch_sync(_ioQueue, ^{
                self.fileManager = [NSFileManager new];
            });
             //app被杀死时发出通知
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(deleteOldFiles)
                                                         name:UIApplicationWillTerminateNotification
                                                       object:nil];
            //app进入后台时发出通知
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(backgroundDeleteOldFiles)
                                                         name:UIApplicationDidEnterBackgroundNotification
                                                       object:nil];
    }
    
    

    当app进入后台或者被杀死时,需要相应的执行方法@selector(backgroundDeleteOldFiles)和@selectors(deleteOldFiles)这两个方法。
    最终这两个方法都是调用的下面的这个方法

    - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock {
      
    }
    

    只不过在backgroundDeleteOldFiles中需要处理任务进入后台请求额外时间的处理,相应的处理代码如下:

    - (void)backgroundDeleteOldFiles {
        Class UIApplicationClass = NSClassFromString(@"UIApplication");
        if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
            return;
        }
        UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
        __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
            // Clean up any unfinished task business by marking where you
            // stopped or ending the task outright.
            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }];
    
       //启动长时间运行的任务并立即返回
        [self deleteOldFilesWithCompletionBlock:^{
            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }];
    }
    

    之后,开始看- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock这个方法中的相应的实现

    - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock  {
       //对于io操作队列,开启一个异步线程,来实现其他的一些东西
        dispatch_async(self.ioQueue, ^{
            NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
    
            // Compute content date key to be used for tests
            NSURLResourceKey cacheContentDateKey = NSURLContentModificationDateKey;
            switch (self.config.diskCacheExpireType) {
                case SDImageCacheConfigExpireTypeAccessDate:
                    cacheContentDateKey = NSURLContentAccessDateKey;
                    break;
    
                case SDImageCacheConfigExpireTypeModificationDate:
                    cacheContentDateKey = NSURLContentModificationDateKey;
                    break;
    
                default:
                    break;
            }
            
            NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, cacheContentDateKey, NSURLTotalFileAllocatedSizeKey];
    
           //这个枚举器为缓存文件预取有用的属性。
            NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL
                                                       includingPropertiesForKeys:resourceKeys
                                                                          options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                     errorHandler:NULL];
    
           //计算国过期的日期,假设self.config.maxCacheAge为7(今天是7月7号),那么得出来的expirationDate的大小为7月2号,删除过期文件只需要删除存储时间是在7月2号之前的就行
            NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.config.maxCacheAge];
            NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *cacheFiles = [NSMutableDictionary dictionary];
            NSUInteger currentCacheSize = 0;
           //1. 删除超过过期日期的文件。
          // 2.为基于大小的清除传递存储文件属性
            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;
                }
                
              //计算当前已经使用的cache大小, - 并将对应file的属性存到cacheFiles中
                NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
                currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
                cacheFiles[fileURL] = resourceValues;
            }
            
           //根据需要移除的文件的url删除文件
            for (NSURL *fileURL in urlsToDelete) {
                [self.fileManager removeItemAtURL:fileURL error:nil];
            }
          //如果我们当前cache的大小已经超过了允许配置的缓存大小,那就删除已经缓存的文件。
            // 删除策略就是,首先删除修改时间更早的缓存文件
            if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
              //直接将当前cache大小降到允许最大的cache大小的一半
                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]];
                                                                         }];
    
             //每次删除file后,就计算此时的cache的大小,直到达到我们预期的缓存
                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();
                });
            }
        });
    }
    

    上面介绍的是当app被杀死或者app进入后台时的处理逻辑,下面继续原本的代码看,看到有一个方法
    //根据key值获取缓存的fileName,使用了MD5转换

    - (nullable NSString *)cachedFileNameForKey:(nullable NSString *)key {
     const char *str = key.UTF8String;
        if (str == NULL) {
            str = "";
        }
        unsigned char r[CC_MD5_DIGEST_LENGTH];
        CC_MD5(str, (CC_LONG)strlen(str), r);
        NSURL *keyURL = [NSURL URLWithString:key];
        NSString *ext = keyURL ? keyURL.pathExtension : key.pathExtension;
        // File system has file name length limit, we need to check if ext is too long, we don't add it to the filename
        if (ext.length > SD_MAX_FILE_EXTENSION_LENGTH) {
            ext = nil;
        }
        NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
                              r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
                              r[11], r[12], r[13], r[14], r[15], ext.length == 0 ? @"" : [NSString stringWithFormat:@".%@", ext]];
        return filename;
    }
    

    之后,获取缓存路径的方法为:

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

    接下来就是一连串的存储图片数据的方法

    - (void)storeImage:(nullable UIImage *)image
                forKey:(nullable NSString *)key
            completion:(nullable SDWebImageNoParamsBlock)completionBlock {
        [self storeImage:image imageData:nil forKey:key toDisk:YES completion:completionBlock];
    }
    
    - (void)storeImage:(nullable UIImage *)image
                forKey:(nullable NSString *)key
                toDisk:(BOOL)toDisk
            completion:(nullable SDWebImageNoParamsBlock)completionBlock {
        [self storeImage:image imageData:nil forKey:key toDisk:toDisk completion:completionBlock];
    }
    
    - (void)storeImage:(nullable UIImage *)image
             imageData:(nullable NSData *)imageData
                forKey:(nullable NSString *)key
                toDisk:(BOOL)toDisk
            completion:(nullable SDWebImageNoParamsBlock)completionBlock {
    }
    

    最终都是调用的第三个方法,

    - (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 = image.sd_memoryCost;
            //将图片以及对应的花费存储到内存NSCache中
            [self.memCache setObject:image forKey:key cost:cost];
        }
        
    //如果允许存储到磁盘中
        if (toDisk) {
            dispatch_async(self.ioQueue, ^{
                @autoreleasepool {
                    NSData *data = imageData;
                    if (!data && image) {
                        //如果我们没有任何数据来检测图像格式,检查它是否包含alpha通道来使用PNG或JPEG格式
                        SDImageFormat format;
                        if (SDCGImageRefContainsAlpha(image.CGImage)) {
                            format = SDImageFormatPNG;
                        } else {
                            format = SDImageFormatJPEG;
                        }
                        //判断图片的格式,用于编码成数据
                        data = [[SDWebImageCodersManager sharedInstance] encodedDataWithImage:image format:format];
                    }
                   //调用storeImageDataToDisk,将图像数据存储到磁盘
                    [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];
        }
        
        // 根据key获取缓存的路径
        NSString *cachePathForKey = [self defaultCachePathForKey:key];
        // 转换成URL
        NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
        
        [imageData writeToURL:fileURL options:self.config.diskCacheWritingOptions error:nil];
        
      //不允许iClound备份
        if (self.config.shouldDisableiCloud) {
            [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
        }
    }
    

    上面讲得是存储方面的操作,下面讲的是查询和检索的操作

    //查询磁盘缓存中图片是否存在
    - (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
        dispatch_async(self.ioQueue, ^{
            BOOL exists = [self _diskImageDataExistsWithKey:key];
            if (completionBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock(exists);
                });
            }
        });
    }
    

    下面有一个从缓存中获取图片对象的方法,

    //首先检查内存中是否有对应缓存,如果有,则将其取出使用,如果没有,则去检查磁盘中是否有对应的缓存,有的话就使用磁盘中的缓存
     - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key {
        // First check the in-memory cache...
        UIImage *image = [self imageFromMemoryCacheForKey:key];
        if (image) {
            return image;
        }
        
        // Second check the disk cache...
        image = [self imageFromDiskCacheForKey:key];
        return image;
    }
    

    还有一个比较复杂的方法

    - (nullable NSData *)diskImageDataForKey:(nullable NSString *)key {
        if (!key) {
            return nil;
        }
        __block NSData *imageData = nil;
    //这个地方为什么要开启一个同步的队列
        dispatch_sync(self.ioQueue, ^{
         //搜索所有的path以获取data
            imageData = [self diskImageDataBySearchingAllPathsForKey:key];
        });
        
        return imageData;
    }
    
    //搜索的策略
    - (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key {
       //首先根据默认的缓存路径尝试获取data,如果获取到,则直接返回
        NSString *defaultPath = [self defaultCachePathForKey:key];
        NSData *data = [NSData dataWithContentsOfFile:defaultPath options:self.config.diskCacheReadingOptions error:nil];
        if (data) {
            return data;
        }
        //在默认路径去除最后的扩展尝试获取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) {
         //尝试从自定义的路径那里获取data,如果获取到,则直接返回
            NSString *filePath = [self cachePathForKey:key inPath:path];
            NSData *imageData = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil];
            if (imageData) {
                return imageData;
            }
            // 对自定义路径去除后面的扩展,从这个路径尝试获取data,如果获取到则直接返回
            imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil];
            if (imageData) {
                return imageData;
            }
        }
    
        return nil;
    }
    
    

    上面获取到的都是NSData,需要将NSData转换成UIImage对象,需要解码,解码的相关的方法为:

    - (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;
        }
    }
    

    之后,获取相关的NSOperation实例

    - (NSOperation *)queryCacheOperationForKey:(NSString *)key done:(SDCacheQueryCompletedBlock)doneBlock {
        return [self queryCacheOperationForKey:key options:0 done:doneBlock];
    }
    
    - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDCacheQueryCompletedBlock)doneBlock {
        if (!key) {
            if (doneBlock) {
                doneBlock(nil, nil, SDImageCacheTypeNone);
            }
            return nil;
        }
        
        // 从内存中获取cache 的image
        UIImage *image = [self imageFromMemoryCacheForKey:key];
        BOOL shouldQueryMemoryOnly = (image && !(options & SDImageCacheQueryDataWhenInMemory));
    //只需要去查询内存,不需要查询磁盘
        if (shouldQueryMemoryOnly) {
            if (doneBlock) {
                doneBlock(image, nil, SDImageCacheTypeMemory);
            }
            return nil;
        }
        
        NSOperation *operation = [NSOperation new];
        void(^queryDiskBlock)(void) =  ^{
            if (operation.isCancelled) {
                // do not call the completion if cancelled
                return;
            }
            
            @autoreleasepool {
                NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
                UIImage *diskImage;
                SDImageCacheType cacheType = SDImageCacheTypeNone;
                if (image) {
                    // the image is from in-memory cache
                    diskImage = image;
                    cacheType = SDImageCacheTypeMemory;
                } else if (diskData) {
                    cacheType = SDImageCacheTypeDisk;
                    // decode image data only if in-memory cache missed
                    diskImage = [self diskImageForKey:key data:diskData options:options];
                    if (diskImage && self.config.shouldCacheImagesInMemory) {
                        NSUInteger cost = diskImage.sd_memoryCost;
                        [self.memCache setObject:diskImage forKey:key cost:cost];
                    }
                }
                
                if (doneBlock) {
                    //当需要同步查询磁盘的数据时,直接调用doneBlock
                    if (options & SDImageCacheQueryDiskSync) {
                        doneBlock(diskImage, diskData, cacheType);
                    } else {
                      //当需要异步查询磁盘数据,同步查询的内存数据,使用dispatch_async
                        dispatch_async(dispatch_get_main_queue(), ^{
                            doneBlock(diskImage, diskData, cacheType);
                        });
                    }
                }
            }
        };
        
       //当需要同步执行这个block时,不需要开辟新的线程,使用原本的线程就好
        if (options & SDImageCacheQueryDiskSync) {
            queryDiskBlock();
        } else {
            //需要异步查询时,用ioQueue执行queryDiskBlock
            dispatch_async(self.ioQueue, queryDiskBlock);
        }
        
        return operation;
    }
    

    上面的代码目前就先看到这里,到这里留有几个疑问:一是SDWebImageCompat.h的实现,里面主要是判断图片的格式;二是SDWebImageCoderManager中的实现,这个类中的实现是将图片编码和解码以及压缩(NSData和UIImage对象的转换),三是各个线程的开辟和使用,特别是最后两个方法涉及的,有点摸不清头脑,需要自己理顺一下。

    SDWebImage源码阅读(一)
    SDWebImage源码阅读(二)
    SDWebImage源码阅读(三)
    SDWebImage源码阅读(四)
    SDWebImage源码阅读(五)
    SDWebImage源码阅读(六)

    相关文章

      网友评论

          本文标题:SDWebImage源码阅读(六)

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