SDWebImage之SDImageCache


SDImageCache和SDWebImageDownloader是SDWebImage庫的最重要的兩個部件,它們一起為SDWebImageManager提供服務,來完成圖片的加載。SDImageCache提供了對圖片的內存緩存、異步磁盤緩存、圖片緩存查詢等功能,下載過的圖片會被緩存到內存,也可選擇保存到本地磁盤,當再次請求相同圖片時直接從緩存中讀取圖片,從而大大提高了加載速度。在SDImageCache中,內存緩存是通過 NSCache的子類AutoPurgeCache來實現的;磁盤緩存是通過 NSFileManager 來實現文件的存儲(默認路徑為/Library/Caches/default/com.hackemist.SDWebImageCache.default),是異步實現的。

下面我們還是一步步來分析它的源碼結構。

1.SDImageCacheType枚舉類型

/**
 緩存類型
 */
typedef NS_ENUM(NSInteger, SDImageCacheType) {
    /**
     * The image wasn't available the SDWebImage caches, but was downloaded from the web.
     */
    SDImageCacheTypeNone,  //不使用 SDWebImage 緩存,從網絡下載
    /**
     * The image was obtained from the disk cache.
     */
    SDImageCacheTypeDisk,  //使用磁盤緩存
    /**
     * The image was obtained from the memory cache.
     */
    SDImageCacheTypeMemory  //使用內存緩存
};

2.Block定義

/**
 查詢回調Block

 @param image 圖片
 @param data 圖片數據
 @param cacheType 緩存類型
 */
typedef void(^SDCacheQueryCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType);

/**
 磁盤緩存檢查回調

 @param isInCache 是否在緩存中
 */
typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache);

/**
 磁盤緩存空間大小計算回調Block

 @param fileCount 文件數量
 @param totalSize 總大小
 */
typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);

3.SDImageCache的屬性 

//SDImageCacheConfig.h
@property (assign, nonatomic) BOOL shouldDecompressImages;  //!<是否在緩存之前解壓圖片,此項操作可以提升性能,但是會消耗較多的內存,默認是YES。注意:如果內存不足,可以置為NO
@property (assign, nonatomic) BOOL shouldDisableiCloud;  //!<是否禁止iCloud備份,默認是YES
@property (assign, nonatomic) BOOL shouldCacheImagesInMemory;  //!<是否啟用內存緩存 默認是YES
@property (assign, nonatomic) NSInteger maxCacheAge;  //!<磁盤緩存保留的最長時間,默認為1周
@property (assign, nonatomic) NSUInteger maxCacheSize;  //!<磁盤緩存最大容量,以字節為單位,默認為0,表示不做限制

//SDImageCache.h
@property (nonatomic, nonnull, readonly) SDImageCacheConfig *config;  //!<SDImageCacheConfig
@property (assign, nonatomic) NSUInteger maxMemoryCost;  //!<內存最大容量
@property (assign, nonatomic) NSUInteger maxMemoryCountLimit;  //!<緩存中可以存放緩存的最大數量,與NSCache相關

//SDImageCache.m
@property (strong, nonatomic, nonnull) NSCache *memCache;  //!<內存緩存
@property (strong, nonatomic, nonnull) NSString *diskCachePath;  //!<磁盤緩存路徑
@property (strong, nonatomic, nullable) NSMutableArray<NSString *> *customPaths;  //!<自定義的緩存路徑
@property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t ioQueue;  //!<磁盤緩存操作的串行隊列

4.SDImageCache的方法

從源碼表面來看,SDImageCache提供的方法很多,但其方法主要圍繞着圖片緩存的添加、刪除、查詢等,只不過每個功能可能有多種實現方式,但本質上是一樣的。

4.1初始化 

/**
 單例方法,返回一個全局的緩存實例

 @return 緩存實例
 */
+ (nonnull instancetype)sharedImageCache {
    static dispatch_once_t once;
    static id instance;
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}

- (instancetype)init {
    return [self initWithNamespace:@"default"];
}

/**
 使用指定的命名空間實例化一個新的緩存存儲

 @param ns 命名空間
 @return 緩存實例
 */
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns {
    NSString *path = [self makeDiskCachePath:ns];
    return [self initWithNamespace:ns diskCacheDirectory:path];
}

/**
 使用指定的命名空間實例化一個新的緩存存儲和目錄

 @param ns 命名空間
 @param directory 緩存所在目錄
 @return 緩存實例
 */
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
                       diskCacheDirectory:(nonnull NSString *)directory {
    if ((self = [super init])) {
        NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
        
        // Create IO serial queue
        _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
        //初始化緩存策略配置對象
        _config = [[SDImageCacheConfig alloc] init];
        
        // Init the memory cache
        // 初始化內存緩存對象
        _memCache = [[AutoPurgeCache alloc] init];
        _memCache.name = fullNamespace;

        // 初始化磁盤緩存路徑
        if (directory != nil) {
            _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
        } else {
            NSString *path = [self makeDiskCachePath:ns];
            _diskCachePath = path;
        }

        dispatch_sync(_ioQueue, ^{
            _fileManager = [NSFileManager new];
        });

#if SD_UIKIT
        // Subscribe to app events
        //當應用收到內存警告的時候,清除內存緩存
        [[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];
#endif
    }

    return self;
}

上面就是SDImageCache的初始化過程,主要是初始化內存緩存對象和初始化磁盤緩存目錄,以及對一些默認參數的賦值。

4.2緩存圖片

/**
 以key為鍵值將圖片image存儲到緩存中

 @param image 圖片
 @param key key
 @param completionBlock 回調Block
 */
- (void)storeImage:(nullable UIImage *)image
            forKey:(nullable NSString *)key
        completion:(nullable SDWebImageNoParamsBlock)completionBlock {
    [self storeImage:image imageData:nil forKey:key toDisk:YES completion:completionBlock];
}

/**
 以key為鍵值將圖片image存儲到緩存中

 @param image 圖片
 @param key key
 @param toDisk 是否寫入磁盤緩存
 @param completionBlock 回調Block
 */
- (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];
}

/**
 把一張圖片存入緩存的具體實現

 @param image 緩存的圖片對象
 @param imageData 緩存的圖片數據
 @param key 緩存對應的key
 @param toDisk 是否緩存到磁盤
 @param 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 memory cache is enabled
    //緩存到內存
    if (self.config.shouldCacheImagesInMemory) {
        //計算緩存數據的大小
        NSUInteger cost = SDCacheCostForImage(image);
        //加入緩存
        [self.memCache setObject:image forKey:key cost:cost];
    }
    
    if (toDisk) {
        //在一個串行隊列中做磁盤緩存操作
        dispatch_async(self.ioQueue, ^{
            @autoreleasepool {
                NSData *data = imageData;
                if (!data && image) {
                    //獲取圖片的類型GIF/PNG等
                    SDImageFormat imageFormatFromData = [NSData sd_imageFormatForImageData:data];
                    //根據指定的SDImageFormat,把圖片轉換為對應的data數據
                    data = [image sd_imageDataAsFormat:imageFormatFromData];
                }
                //把處理好了的數據存入磁盤
                [self storeImageDataToDisk:data forKey:key];
            }
            
            if (completionBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock();
                });
            }
        });
    } else {
        if (completionBlock) {
            completionBlock();
        }
    }
}

/**
 把圖片資源存入磁盤

 @param imageData 圖片數據
 @param key key
 */
- (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key {
    if (!imageData || !key) {
        return;
    }
    
    [self checkIfQueueIsIOQueue];
    //緩存目錄是否已經初始化
    if (![_fileManager fileExistsAtPath:_diskCachePath]) {
        [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    // get cache Path for image key
    //獲取key對應的完整緩存路徑
    NSString *cachePathForKey = [self defaultCachePathForKey:key];
    // transform to NSUrl
    NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
    //把數據存入路徑
    [_fileManager createFileAtPath:cachePathForKey contents:imageData attributes:nil];
    
    // disable iCloud backup
    if (self.config.shouldDisableiCloud) {
        [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
}

4.3查詢圖片

/**
 根據key判斷磁盤緩存中是否存在圖片

 @param key key
 @param completionBlock 回調Block
 */
- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
    dispatch_async(_ioQueue, ^{
        BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];

        // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
        // checking the key with and without the extension
        if (!exists) {
            exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key].stringByDeletingPathExtension];
        }

        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(exists);
            });
        }
    });
}

/**
 根據key獲取緩存在內存中的圖片

 @param key key
 @return 緩存的圖片
 */
- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key {
    return [self.memCache objectForKey:key];
}

/**
 根據key獲取緩存在磁盤中的圖片

 @param key key
 @return 緩存的圖片
 */
- (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;
}

/**
 根據key獲取緩存圖片(先從內存中搜索,再去磁盤中搜索)

 @param key key
 @return 緩存的圖片
 */
- (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;
}

/**
 根據指定的key,獲取存儲在磁盤上的數據

 @param key 圖片對應的key
 @return 返回圖片數據
 */
- (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key {
    //獲取key對應的path
    NSString *defaultPath = [self defaultCachePathForKey:key];
    NSData *data = [NSData dataWithContentsOfFile:defaultPath];
    if (data) {
        return data;
    }

    // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
    // checking the key with and without the extension
    //如果key沒有后綴名,則會走到這里通過這里讀取
    data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension];
    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];
        if (imageData) {
            return imageData;
        }

        // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
        // checking the key with and without the extension
        imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension];
        if (imageData) {
            return imageData;
        }
    }

    return nil;
}

/**
 根據指定的key獲取image對象

 @param key key
 @return image對象
 */
- (nullable UIImage *)diskImageForKey:(nullable NSString *)key {
    //獲取磁盤數據
    NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
    if (data) {
        UIImage *image = [UIImage sd_imageWithData:data];
        image = [self scaledImageForKey:key image:image];
        if (self.config.shouldDecompressImages) {
            image = [UIImage decodedImageWithImage:image];
        }
        return image;
    }
    else {
        return nil;
    }
}

- (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image {
    return SDScaledImageForKey(key, image);
}

/**
 在緩存中查詢對應key的數據

 @param key 要查詢的key
 @param doneBlock 查詢結束以后的回調Block
 @return 返回做查詢操作的NSOperation
 */
- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock {
    if (!key) {
        if (doneBlock) {
            doneBlock(nil, nil, SDImageCacheTypeNone);
        }
        return nil;
    }

    // First check the in-memory cache...
    //首先從內存中查找圖片
    UIImage *image = [self imageFromMemoryCacheForKey:key];
    if (image) {
        NSData *diskData = nil;
        if ([image isGIF]) {
            diskData = [self diskImageDataBySearchingAllPathsForKey:key];
        }
        if (doneBlock) {
            doneBlock(image, diskData, SDImageCacheTypeMemory);
        }
        return nil;
    }
    //新建一個NSOperation來獲取磁盤圖片
    NSOperation *operation = [NSOperation new];
    dispatch_async(self.ioQueue, ^{
        if (operation.isCancelled) {
            // do not call the completion if cancelled
            return;
        }
        //在一個自動釋放池中處理圖片從磁盤加載
        @autoreleasepool {
            NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
            UIImage *diskImage = [self diskImageForKey:key];
            if (diskImage && self.config.shouldCacheImagesInMemory) {
                NSUInteger cost = SDCacheCostForImage(diskImage);
                //把從磁盤取出的緩存圖片加入內存緩存中
                [self.memCache setObject:diskImage forKey:key cost:cost];
            }
            //圖片處理完成以后回調Block
            if (doneBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    doneBlock(diskImage, diskData, SDImageCacheTypeDisk);
                });
            }
        }
    });

    return operation;
}

4.4刪除圖片

#pragma mark - Remove Ops

/**
 通過key從磁盤和內存中移除緩存

 @param key key
 @param completion 回調Block
 */
- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion {
    [self removeImageForKey:key fromDisk:YES withCompletion:completion];
}

/**
 移除指定key對應的緩存數據

 @param key key
 @param fromDisk 是否也清除磁盤緩存
 @param 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) {
        dispatch_async(self.ioQueue, ^{
            [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
            
            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion();
                });
            }
        });
    } else if (completion){
        completion();
    }
    
}

#pragma mark - Cache clean Ops 內存緩存清理相關操作

/**
 清理當前SDImageCache對象的內存緩存
 */
- (void)clearMemory {
    [self.memCache removeAllObjects];
}

/**
 移除所有的磁盤緩存圖片數據

 @param completion 移除完成以后回調
 */
- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion {
    dispatch_async(self.ioQueue, ^{
        [_fileManager removeItemAtPath:self.diskCachePath error:nil];
        [_fileManager createDirectoryAtPath:self.diskCachePath
                withIntermediateDirectories:YES
                                 attributes:nil
                                      error:NULL];

        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion();
            });
        }
    });
}

- (void)deleteOldFiles {
    [self deleteOldFilesWithCompletionBlock:nil];
}

/**
 當應用終止或者進入后台都會調用這個方法來清除緩存圖片
 這里會根據圖片存儲時間來清理圖片,默認是一周,從最老的圖片開始清理。如果圖片緩存空間小於一個規定值,則不考慮

 @param completionBlock 清除完成以后的回調
 */
- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock {
    dispatch_async(self.ioQueue, ^{
        //獲取磁盤緩存的默認根目錄
        NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
        NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];

        // This enumerator prefetches useful properties for our cache files.
        NSDirectoryEnumerator *fileEnumerator = [_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;

        // Enumerate all of the files in the cache directory.  This loop has two purposes:
        //
        //  1. Removing files that are older than the expiration date.
        //  2. Storing file attributes for the size-based cleanup pass.
        //迭代緩存目錄。有兩個目的:
        //1 刪除比指定日期更老的圖片
        //2 記錄文件的大小,以提供給后面刪除使用
        NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init];
        for (NSURL *fileURL in fileEnumerator) {
            NSError *error;
            //獲取指定url對應文件的指定三種屬性的key和value
            NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];

            // Skip directories and errors.
            //如果是文件夾則返回
            if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) {
                continue;
            }

            // Remove files that are older than the expiration date;
            //獲取指定url文件對應的修改日期
            NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
            //如果修改日期大於指定日期,則加入要移除的數組里
            if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
                [urlsToDelete addObject:fileURL];
                continue;
            }

            // Store a reference to this file and account for its total size.
            //獲取指定的url對應的文件的大小,並且把url與對應大小存入一個字典中
            NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
            currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
            cacheFiles[fileURL] = resourceValues;
        }
        //刪除所有最后修改日期大於指定日期的所有文件
        for (NSURL *fileURL in urlsToDelete) {
            [_fileManager removeItemAtURL:fileURL error:nil];
        }

        // 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) {
            // Target half of our maximum cache size for this cleanup pass.
            const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2;

            // Sort the remaining cache files by their last modification time (oldest first).
            //根據文件創建的時間排序
            NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
                                                                     usingComparator:^NSComparisonResult(id obj1, id obj2) {
                                                                         return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
                                                                     }];

            // Delete files until we fall below our desired cache size.
            //迭代刪除緩存,直到緩存大小是默認緩存大小的一半
            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();
            });
        }
    });
}

#if SD_UIKIT

/**
 應用進入后台的時候,調用這個方法
 */
- (void)backgroundDeleteOldFiles {
    Class UIApplicationClass = NSClassFromString(@"UIApplication");
    if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
        return;
    }
    UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
    //如果backgroundTask對應的時間結束了,任務還沒有處理完成,則直接終止任務
    __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;
    }];

    // Start the long-running task and return immediately.
    //圖片清理結束以后,處理完成
    [self deleteOldFilesWithCompletionBlock:^{
        //清理完成以后,終止任務
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
}
#endif

4.5其他方法

#pragma mark - Cache paths

/**
 添加只讀的緩存路徑

 @param path 路徑
 */
- (void)addReadOnlyCachePath:(nonnull NSString *)path {
    if (!self.customPaths) {
        self.customPaths = [NSMutableArray new];
    }

    if (![self.customPaths containsObject:path]) {
        [self.customPaths addObject:path];
    }
}

/**
 獲取指定key對應的完整緩存路徑

 @param key 對應一張圖片,比如圖片的名字
 @param path 指定根目錄
 @return 完整路徑
 */
- (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path {
    NSString *filename = [self cachedFileNameForKey:key];
    return [path stringByAppendingPathComponent:filename];
}

- (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key {
    return [self cachePathForKey:key inPath:self.diskCachePath];
}

/**
 MD5加密

 @param key key
 @return 加密后的數據
 */
- (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);
    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], [key.pathExtension isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", key.pathExtension]];

    return filename;
}

/**
 圖片緩存目錄

 @param fullNamespace 自定義子目錄名稱
 @return 完整目錄
 */
- (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace {
    NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [paths[0] stringByAppendingPathComponent:fullNamespace];
}

#pragma mark - Cache Info

/**
 磁盤緩存使用的大小

 @return 磁盤緩存的大小
 */
- (NSUInteger)getSize {
    __block NSUInteger size = 0;
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        for (NSString *fileName in fileEnumerator) {
            NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
            NSDictionary<NSString *, id> *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
            size += [attrs fileSize];
        }
    });
    return size;
}

/**
 磁盤緩存的圖片數量

 @return 緩存的圖片數量
 */
- (NSUInteger)getDiskCount {
    __block NSUInteger count = 0;
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        count = fileEnumerator.allObjects.count;
    });
    return count;
}

/**
 異步計算磁盤緩存的大小

 @param completionBlock 回調Block
 */
- (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock {
    NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];

    dispatch_async(self.ioQueue, ^{
        NSUInteger fileCount = 0;
        NSUInteger totalSize = 0;

        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
                                                   includingPropertiesForKeys:@[NSFileSize]
                                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                 errorHandler:NULL];

        for (NSURL *fileURL in fileEnumerator) {
            NSNumber *fileSize;
            [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
            totalSize += fileSize.unsignedIntegerValue;
            fileCount += 1;
        }

        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(fileCount, totalSize);
            });
        }
    });
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM