SDWebImage學(xué)習(xí)筆記(一):概要介紹+SDImageCache

該類庫所提供的功能

1寨躁、帶有管理網(wǎng)絡(luò)圖片下載和緩存的UIImageView類別穆碎;
2、支持異步下載职恳;
3所禀、支持異步內(nèi)存+磁盤緩存,自動(dòng)清理過期緩存话肖;
4北秽、支持Gif葡幸;
5最筒、支持WebP;
6蔚叨、支持圖片后臺(tái)解壓床蜘;
7、確保同樣的URL不會(huì)下載多次蔑水;
8邢锯、偽造的URL不會(huì)嘗試重新下載;
9搀别、確保主線程不會(huì)堵塞丹擎;
10、高性能歇父;
11蒂培、使用GCD和ARC;
12榜苫、支持64位护戳;

目錄結(jié)構(gòu)

1、Downloader:圖片下載相關(guān)類
2垂睬、Cache:圖片緩存處理相關(guān)類
3媳荒、Utils:SDWebImageManager管理SDWebImageDownloader和SDImageCache;SDWebImageDecoder用來解壓圖片驹饺; SDWebImagePrefetcher預(yù)加載圖片钳枕;
4、Categories:控件類目擴(kuò)展

F884FC26-13A3-4781-8094-2733EC2A7FF8.png

SDImageCache類結(jié)構(gòu)

SDImageCache:主要提供三種緩存方式( SDImageCacheTypeNone赏壹、SDImageCacheTypeDisk么伯、SDImageCacheTypeMemory),其中圖片的磁盤緩存寫操作采用異步處理方式卡儒。一般情況下田柔,磁盤緩存的操作都采用異步處理俐巴。下面是 文件#import “SDImageCache.m”
中類實(shí)現(xiàn)的結(jié)構(gòu):

屏幕快照 2016-07-06 上午10.55.46.png

屏幕快照 2016-07-06 上午10.56.14.png

緩存圖片包括4個(gè)方法:

- (void)storeImage:(UIImage *)image forKey:(NSString *)key;
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;
- (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key;

從緩存中獲取圖片包括3個(gè)方法(第一個(gè)方法異步獲取):

- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;

根據(jù)鍵值從緩存中清除圖片包括4個(gè)方法(全部方法都是異步操作):

- (void)removeImageForKey:(NSString *)key;
- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;

清理緩存包括5個(gè)方法:

- (void)clearMemory;
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;
- (void)clearDisk;
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock;
- (void)cleanDisk;

根據(jù)鍵值判斷圖片是否存在磁盤中(第一個(gè)方法異步獲扔脖):

- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
- (BOOL)diskImageExistsWithKey:(NSString *)key;

其它方法欣舵,計(jì)算磁盤緩存大小、緩存中圖片數(shù)缀磕、緩存中是否存在鍵值對(duì)應(yīng)的圖片等缘圈。

代碼注釋

/*
 * This file is part of the SDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "SDImageCache.h"
#import "SDWebImageDecoder.h"
#import "UIImage+MultiFormat.h"
#import <CommonCrypto/CommonDigest.h>

// See https://github.com/rs/SDWebImage/pull/1141 for discussion
#pragma mark -----內(nèi)存緩存類:添加觀察者,內(nèi)存警告時(shí)袜蚕,清空內(nèi)存緩存-----
@interface AutoPurgeCache : NSCache
@end

@implementation AutoPurgeCache

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

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];

}

@end

// 緩存生命期1周:1 week
static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7;
// PNG signature bytes and data (below)
static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
// PNG簽名的數(shù)據(jù):裝載kPNGSignatureBytes
static NSData *kPNGSignatureData = nil;

BOOL ImageDataHasPNGPreffix(NSData *data);

/**
 *  ImageData是否含有PNG前綴
 *
 *  @param data 圖片數(shù)據(jù)
 *
 *  @return 圖片是否含有PNG前綴
 */
BOOL ImageDataHasPNGPreffix(NSData *data) {
    NSUInteger pngSignatureLength = [kPNGSignatureData length];
    if ([data length] >= pngSignatureLength) {
        if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) {
            return YES;
        }
    }

    return NO;
}

/**
 *  計(jì)算圖片所占內(nèi)存大小
 *
 *  @param image <#image description#>
 *
 *  @return <#return value description#>
 */
FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
    // 計(jì)算圖片所消耗的內(nèi)存注意乘以屏幕的比例因子
    return image.size.height * image.size.width * image.scale * image.scale;
}

#pragma mark -----圖片緩存類-----
@interface SDImageCache ()

// 內(nèi)存緩存
@property (strong, nonatomic) NSCache *memCache;
// 磁盤緩存路徑
@property (strong, nonatomic) NSString *diskCachePath;
// 保存緩存路徑的數(shù)組
@property (strong, nonatomic) NSMutableArray *customPaths;
// 執(zhí)行處理輸入輸出的等待隊(duì)列
@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue;

@end


@implementation SDImageCache {
    NSFileManager *_fileManager;
}

#pragma mark -- 單例
+ (SDImageCache *)sharedImageCache {
    static dispatch_once_t once;
    static id instance;
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}

#pragma mark -- 初始化
- (id)init {
    // 默認(rèn)命名空間default糟把,也可以自定義命名空間
    return [self initWithNamespace:@"default"];
}

- (id)initWithNamespace:(NSString *)ns {
    // path = "/var/mobile/Containers/Data/Application/382D0176-0BC4-44E3-98FF-095D02B85D38/Library/Caches/default"
    NSString *path = [self makeDiskCachePath:ns];
    return [self initWithNamespace:ns diskCacheDirectory:path];
}

- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory {
    if ((self = [super init])) {
        // com.hackemist.SDWebImageCache.default
        NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];

        // 初始化PNG簽名數(shù)據(jù)initialise PNG signature data
        kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8];

        // 初始化執(zhí)行處理輸入輸出的等待隊(duì)列:Create IO serial queue
        _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);

        // 初始化緩存生命期: Init default values
        _maxCacheAge = kDefaultCacheMaxCacheAge;

        // 初始化內(nèi)存緩存:Init the memory cache
        _memCache = [[AutoPurgeCache alloc] init];
        _memCache.name = fullNamespace;

        // 初始化硬盤緩存:Init the disk cache
        if (directory != nil) {
            // /var/mobile/Containers/Data/Application/3EC2CFBB-6B30-4E4C-8CFE-11B717DEC9BE/Library/Caches/default/com.hackemist.SDWebImageCache.default
            _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
        } else {
            NSString *path = [self makeDiskCachePath:ns];
            _diskCachePath = path;
        }

        // 是否解壓圖片:Set decompression to YES
        _shouldDecompressImages = YES;

        // 是否開啟內(nèi)存緩存:memory cache enabled
        _shouldCacheImagesInMemory = YES;

        // 設(shè)置默認(rèn)不使用iCloud:Disable iCloud
        _shouldDisableiCloud = YES;

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

#if TARGET_OS_IOS
        // Subscribe to app events
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(clearMemory)
                                                     name:UIApplicationDidReceiveMemoryWarningNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(cleanDisk)
                                                     name:UIApplicationWillTerminateNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(backgroundCleanDisk)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
#endif
    }

    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    SDDispatchQueueRelease(_ioQueue);
}

#pragma mark -- 圖片路徑操作
/**
 *  往數(shù)組中添加唯一緩存路徑
 *
 *  @param path 路徑
 */
- (void)addReadOnlyCachePath:(NSString *)path {
    if (!self.customPaths) {
        self.customPaths = [NSMutableArray new];
    }

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

/**
 *  返回緩存完整路徑骂删,其中文件名是根據(jù)key值生成的MD5值
 *
 *  @param key  key
 *  @param path 路徑
 *
 *  @return <#return value description#>
 */
- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path {
    NSString *filename = [self cachedFileNameForKey:key];// 508746268d43f962e80def6392aff711.35786508303135633
    return [path stringByAppendingPathComponent:filename];// /var/mobile/Containers/Data/Application/111DBEDD-3D5E-457D-867F-EC0E08260A46/Library/Caches/default/com.hackemist.SDWebImageCache.default/508746268d43f962e80def6392aff711.35786508303135633
}

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

#pragma mark SDImageCache (private)
/**
 *  根據(jù)key值生成文件名:采用MD5
 *
 *  @param key key
 *
 *  @return 文件名
 */
- (NSString *)cachedFileNameForKey:(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;
}

#pragma mark ImageCache
#pragma mark -- 初始化磁盤緩存路徑
/**
 *  初始化磁盤緩存路徑
 *
 *  @param fullNamespace 磁盤緩存命名空間:默認(rèn)為default
 *
 *  @return 磁盤緩存路徑
 */
-(NSString *)makeDiskCachePath:(NSString*)fullNamespace{
    // /var/mobile/Containers/Data/Application/382D0176-0BC4-44E3-98FF-095D02B85D38/Library/Caches
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [paths[0] stringByAppendingPathComponent:fullNamespace];
}

#pragma mark -- 緩存圖片
/**
 *  緩存圖片
 *
 *  @param image       圖片
 *  @param recalculate 是否重新計(jì)算
 *  @param imageData   imageData
 *  @param key         緩存的key
 *  @param toDisk      是否緩存到磁盤
 */
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk {
    if (!image || !key) {
        return;
    }
    
    // 緩存到內(nèi)存
    if (self.shouldCacheImagesInMemory) {
        NSUInteger cost = SDCacheCostForImage(image);
        [self.memCache setObject:image forKey:key cost:cost];
    }

    // 緩存到磁盤锭吨,采用異步操作
    if (toDisk) {
        dispatch_async(self.ioQueue, ^{
            NSData *data = imageData;

            if (image && (recalculate || !data)) {
#if TARGET_OS_IPHONE
                // We need to determine if the image is a PNG or a JPEG
                // PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html)
                // The first eight bytes of a PNG file always contain the following (decimal) values:
                // 137 80 78 71 13 10 26 10
                // PNG圖片有統(tǒng)一的簽名較易甄別,前8個(gè)字節(jié)通常包含:137 80 78 71 13 10 26 10

                // If the imageData is nil (i.e. if trying to save a UIImage directly or the image was transformed on download)
                // and the image has an alpha channel, we will consider it PNG to avoid losing the transparency
                // 如圖片的imageData為空(如果試圖直接保存一個(gè)UIImage 或者 圖片是由下載轉(zhuǎn)換得來)扶镀,且圖片含有alpha通道凿傅,將進(jìn)行PNG緩存處理避免失去透明度
                int alphaInfo = CGImageGetAlphaInfo(image.CGImage);
                BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone ||
                                  alphaInfo == kCGImageAlphaNoneSkipFirst ||
                                  alphaInfo == kCGImageAlphaNoneSkipLast);
                BOOL imageIsPng = hasAlpha;

                // But if we have an image data, we will look at the preffix
                if ([imageData length] >= [kPNGSignatureData length]) {
                    imageIsPng = ImageDataHasPNGPreffix(imageData);
                }

                if (imageIsPng) {
                    data = UIImagePNGRepresentation(image);
                }
                else {
                    data = UIImageJPEGRepresentation(image, (CGFloat)1.0);
                }
#else
                data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil];
#endif
            }

            [self storeImageDataToDisk:data forKey:key];
        });
    }
}

- (void)storeImage:(UIImage *)image forKey:(NSString *)key {
    [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES];
}

- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk {
    [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk];
}

/**
 *  保存圖片imageData到磁盤
 *
 *  @param imageData imageData
 *  @param key       緩存的key
 */
- (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key {
    
    if (!imageData) {
        return;
    }
    
    // 如果不存在該路徑缠犀,則創(chuàng)建
    if (![_fileManager fileExistsAtPath:_diskCachePath]) {
        [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    // 根據(jù)key獲取緩存路徑:get cache Path for image key
    // /var/mobile/Containers/Data/Application/752F97A5-F9EB-4C6C-A96B-2C785087B4A6/Library/Caches/default/com.hackemist.SDWebImageCache.default/fcc1e50837ec9a5d0cca14cda3339ca7.webp
    NSString *cachePathForKey = [self defaultCachePathForKey:key];
    // 將緩存路徑轉(zhuǎn)換為URL:transform to NSUrl
    // file:///var/mobile/Containers/Data/Application/752F97A5-F9EB-4C6C-A96B-2C785087B4A6/Library/Caches/default/com.hackemist.SDWebImageCache.default/fcc1e50837ec9a5d0cca14cda3339ca7.webp
    NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
    
    // 保存數(shù)據(jù)
    [_fileManager createFileAtPath:cachePathForKey contents:imageData attributes:nil];
    
    // 關(guān)閉iCloud備份:disable iCloud backup
    if (self.shouldDisableiCloud) {
        [fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
}

#pragma mark -- 磁盤中是否存在圖片
/**
 *  根據(jù)key判斷是否Image是否存在磁盤中
 *
 *  @param key key
 *
 *  @return <#return value description#>
 */
- (BOOL)diskImageExistsWithKey:(NSString *)key {
    BOOL exists = NO;
    
    // this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance
    // from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely.
    exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]];

    // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
    // 去掉路徑的擴(kuò)展名后在進(jìn)行檢查:checking the key with and without the extension
    if (!exists) {
        exists = [[NSFileManager defaultManager] fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
    }
    
    return exists;
}

/**
 *  根據(jù)key判斷是否Image是否存在磁盤中:異步處理
 *
 *  @param key             key
 *  @param completionBlock Image是否存在磁盤中回調(diào)
 */
- (void)diskImageExistsWithKey:(NSString *)key completion:(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);
            });
        }
    });
}

#pragma mark -- 根據(jù)key從磁盤或內(nèi)存中獲取圖片
/**
 *  根據(jù)key從內(nèi)存中獲取圖片
 *
 *  @param key key
 *
 *  @return <#return value description#>
 */
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key {
    return [self.memCache objectForKey:key];
}

/**
 *  根據(jù)key從磁盤緩存中獲取圖片
 *
 *  @param key key
 *
 *  @return <#return value description#>
 */
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key {
    // 首先查看內(nèi)存的緩存中是否含有該key所對(duì)應(yīng)的圖片,在檢查磁盤緩存
    
    // First check the in-memory cache...
    UIImage *image = [self imageFromMemoryCacheForKey:key];
    if (image) {
        return image;
    }

    // Second check the disk cache...
    UIImage *diskImage = [self diskImageForKey:key];
    if (diskImage && self.shouldCacheImagesInMemory) {
        // 將圖片寫入內(nèi)存緩存
        NSUInteger cost = SDCacheCostForImage(diskImage);
        [self.memCache setObject:diskImage forKey:key cost:cost];
    }

    return diskImage;
}

/**
 *  根據(jù)key在磁盤緩存中搜索圖片
 *
 *  @param key key
 *
 *  @return 圖片數(shù)據(jù)
 */
- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key {
    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
    data = [NSData dataWithContentsOfFile:[defaultPath stringByDeletingPathExtension]];
    if (data) {
        return data;
    }

    NSArray *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;
}

- (UIImage *)diskImageForKey:(NSString *)key {
    NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
    if (data) {
        UIImage *image = [UIImage sd_imageWithData:data];
        // 根據(jù)圖片的scale 或 圖片中的圖片組 重新計(jì)算返回圖片
        image = [self scaledImageForKey:key image:image];
        if (self.shouldDecompressImages) {
            image = [UIImage decodedImageWithImage:image];
        }
        return image;
    }
    else {
        return nil;
    }
}

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

/**
 *  根據(jù)key從磁盤緩存中獲取圖片:異步操作
 *
 *  @param key       key
 *  @param doneBlock 根據(jù)key從磁盤緩存中獲取圖片回調(diào)
 *
 *  @return <#return value description#>
 */
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
    if (!doneBlock) {
        return nil;
    }

    if (!key) {
        doneBlock(nil, SDImageCacheTypeNone);
        return nil;
    }

    // First check the in-memory cache...
    UIImage *image = [self imageFromMemoryCacheForKey:key];
    if (image) {
        doneBlock(image, SDImageCacheTypeMemory);
        return nil;
    }

    NSOperation *operation = [NSOperation new];
    dispatch_async(self.ioQueue, ^{
        if (operation.isCancelled) {
            return;
        }

        // 這里使用自動(dòng)釋放池聪舒,自己的理解:里面的操作內(nèi)存消耗過大辨液,需要在系統(tǒng)回收的時(shí)候,優(yōu)先箱残、及時(shí)回收自動(dòng)釋放池中分配的對(duì)象滔迈,優(yōu)化內(nèi)存使用。
        @autoreleasepool {
            UIImage *diskImage = [self diskImageForKey:key];
            if (diskImage && self.shouldCacheImagesInMemory) {
                // 將圖片寫入內(nèi)存緩存
                NSUInteger cost = SDCacheCostForImage(diskImage);
                [self.memCache setObject:diskImage forKey:key cost:cost];
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                doneBlock(diskImage, SDImageCacheTypeDisk);
            });
        }
    });

    return operation;
}

#pragma mark -- 根據(jù)key從緩存中清除圖片
- (void)removeImageForKey:(NSString *)key {
    [self removeImageForKey:key withCompletion:nil];
}

- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion {
    [self removeImageForKey:key fromDisk:YES withCompletion:completion];
}

- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk {
    [self removeImageForKey:key fromDisk:fromDisk withCompletion:nil];
}

/**
 *  根據(jù)key從緩存中清除圖片
 *
 *  @param key        key
 *  @param fromDisk   是否磁盤緩存
 *  @param completion 緩存圖片清除回調(diào)
 */
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion {
    
    if (key == nil) {
        return;
    }

    // 內(nèi)存緩存清除
    if (self.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 -- 設(shè)置
- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
    self.memCache.totalCostLimit = maxMemoryCost;
}

- (NSUInteger)maxMemoryCost {
    return self.memCache.totalCostLimit;
}

- (NSUInteger)maxMemoryCountLimit {
    return self.memCache.countLimit;
}

- (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit {
    self.memCache.countLimit = maxCountLimit;
}

#pragma mark -- 清空 或清除 緩存
/**
 *  清空內(nèi)存緩存
 */
- (void)clearMemory {
    [self.memCache removeAllObjects];
}

/**
 *  清空磁盤緩存
 */
- (void)clearDisk {
    [self clearDiskOnCompletion:nil];
}

/**
 *  清空磁盤緩存
 *
 *  @param completion 磁盤緩存清空回調(diào)
 */
- (void)clearDiskOnCompletion:(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)cleanDisk {
    [self cleanDiskWithCompletionBlock:nil];
}

/**
 *  清除磁盤緩存被辑,異步操作:1燎悍、清除過期的緩存文件;2敷待、緩存超過設(shè)定閾值時(shí)间涵,按時(shí)間順序刪除緩存中的圖片,直到緩存剩余空間達(dá)閾值的一半
 *
 *  @param completion 磁盤緩存清除回調(diào)
 */
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock {
    dispatch_async(self.ioQueue, ^{
        // dickCacheURL:file:///var/mobile/Containers/Data/Application/E42DF859-9AF1-46B3-B518-FB62ECE73D33/Library/Caches/default/com.hackemist.SDWebImageCache.default/
        NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
        // resourceKeys包含要了解的屬性:允許判斷遍歷到的URL所指對(duì)象是否是目錄榜揖、允許判斷遍歷返回的URL所指項(xiàng)目的最后修改時(shí)間勾哩、URL目錄中所分配的空間大小
        NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];

        // 使用目錄枚舉器獲取緩存文件:This enumerator prefetches useful properties for our cache files.
        // 使用NSdirectoryEnumerator遍歷所有的緩存文件,獲取文件屬性举哟,如我們需要的文件大小信息思劳,是不會(huì)有性能問題的。NSdirectoryEnumerator獲取文件屬性是通過查看文件的inode數(shù)據(jù)妨猩,并不需要想象中的fileopen和fileclose潜叛。
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
                                                   includingPropertiesForKeys:resourceKeys
                                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                 errorHandler:NULL];

        // 計(jì)算過期時(shí)間,默認(rèn)1周以前的緩存文件為過期
        NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge];
        NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary]; // 當(dāng)前保存下來文件的fileURL
        NSUInteger currentCacheSize = 0; // 當(dāng)前保存下來文件的總內(nèi)存大小

        // 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 *urlsToDelete = [[NSMutableArray alloc] init]; // 將會(huì)刪除的文件fileURL數(shù)組
        for (NSURL *fileURL in fileEnumerator) {
            NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL];

            // 跳過目錄:Skip directories.
            if ([resourceValues[NSURLIsDirectoryKey] boolValue]) {
                continue;
            }

            // 記錄超過過期日期文件的fileURL:Remove files that are older than the expiration date;
            NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
            if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
                [urlsToDelete addObject:fileURL];
                continue;
            }

            // 保存保留下來的文件的引用并計(jì)算文件總的大小:Store a reference to this file and account for its total size.
            NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
            currentCacheSize += [totalAllocatedSize unsignedIntegerValue];
            [cacheFiles setObject:resourceValues forKey:fileURL];
        }
        
        // 刪除緩存中過期的文件
        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.
        // 當(dāng)設(shè)置的maxCacheSize > 0 且 當(dāng)前緩存中的文件所占內(nèi)存大于設(shè)置的最大緩存時(shí)椒舵,按時(shí)間順序刪除文件蚂踊,直到緩存剩余空間達(dá)閾值的一半
        if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) {
            // 清除緩存目標(biāo)是最大緩存的一半:Target half of our maximum cache size for this cleanup pass.
            const NSUInteger desiredCacheSize = self.maxCacheSize / 2;

            // 緩存文件排序,最老的文件先清除:Sort the remaining cache files by their last modification time (oldest first).
            NSArray *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 *resourceValues = cacheFiles[fileURL];
                    NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
                    currentCacheSize -= [totalAllocatedSize unsignedIntegerValue];

                    if (currentCacheSize < desiredCacheSize) {
                        break;
                    }
                }
            }
        }
        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock();
            });
        }
    });
}

/**
 *  后臺(tái)清理磁盤緩存:收到UIApplicationDidEnterBackgroundNotification時(shí)笔宿,在手機(jī)系統(tǒng)后臺(tái)進(jìn)行如上面描述的異步磁盤緩存清理
 */
- (void)backgroundCleanDisk {
    Class UIApplicationClass = NSClassFromString(@"UIApplication");
    if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
        return;
    }
    
    // 使用sharedApplication開啟后臺(tái)任務(wù)cleanDiskWithCompletionBlock:
    UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // 清理任何未完成的任務(wù)作業(yè)犁钟,標(biāo)記完全停止或結(jié)束任務(wù):Clean up any unfinished task business by marking where you stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // 開始長(zhǎng)時(shí)間后臺(tái)運(yùn)行的任務(wù)并且立即return:Start the long-running task and return immediately.
    [self cleanDiskWithCompletionBlock:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
}

#pragma mark -- 計(jì)算緩存大小、緩存中圖片數(shù)
/**
 *  同步操作:獲取緩存中所有文件的大小
 *
 *  @return <#return value description#>
 */
- (NSUInteger)getSize {
    __block NSUInteger size = 0;
    
    // 需要同步操作:等待隊(duì)列self.ioQueue中的任務(wù)執(zhí)行完后(有可能隊(duì)列中的任務(wù)正在添加圖片或者刪除圖片操作)泼橘,再進(jìn)行獲取文件大小計(jì)算
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        for (NSString *fileName in fileEnumerator) {
            NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
            NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
            size += [attrs fileSize];
        }
    });
    return size;
}

/**
 *  同步操作:獲取磁盤緩存中圖片數(shù)
 *
 *  @return <#return value description#>
 */
- (NSUInteger)getDiskCount {
    __block NSUInteger count = 0;
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        count = [[fileEnumerator allObjects] count];
    });
    return count;
}

/**
 *  異步操作:獲取緩存中圖片數(shù)及圖片所占內(nèi)存總大小
 *
 *  @param completionBlock <#completionBlock description#>
 */
- (void)calculateSizeWithCompletionBlock:(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);
            });
        }
    });
}

@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末涝动,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子炬灭,更是在濱河造成了極大的恐慌醋粟,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,104評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件担败,死亡現(xiàn)場(chǎng)離奇詭異昔穴,居然都是意外死亡镰官,警方通過查閱死者的電腦和手機(jī)提前,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泳唠,“玉大人狈网,你說我怎么就攤上這事”啃龋” “怎么了拓哺?”我有些...
    開封第一講書人閱讀 168,697評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)脖母。 經(jīng)常有香客問我士鸥,道長(zhǎng),這世上最難降的妖魔是什么谆级? 我笑而不...
    開封第一講書人閱讀 59,836評(píng)論 1 298
  • 正文 為了忘掉前任烤礁,我火速辦了婚禮,結(jié)果婚禮上肥照,老公的妹妹穿的比我還像新娘脚仔。我一直安慰自己,他們只是感情好舆绎,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,851評(píng)論 6 397
  • 文/花漫 我一把揭開白布鲤脏。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪猎醇。 梳的紋絲不亂的頭發(fā)上窥突,一...
    開封第一講書人閱讀 52,441評(píng)論 1 310
  • 那天,我揣著相機(jī)與錄音硫嘶,去河邊找鬼波岛。 笑死,一個(gè)胖子當(dāng)著我的面吹牛音半,可吹牛的內(nèi)容都是我干的则拷。 我是一名探鬼主播,決...
    沈念sama閱讀 40,992評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼曹鸠,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼煌茬!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起彻桃,我...
    開封第一講書人閱讀 39,899評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤坛善,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后邻眷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體眠屎,經(jīng)...
    沈念sama閱讀 46,457評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,529評(píng)論 3 341
  • 正文 我和宋清朗相戀三年肆饶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了改衩。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,664評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡驯镊,死狀恐怖葫督,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情板惑,我是刑警寧澤橄镜,帶...
    沈念sama閱讀 36,346評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站冯乘,受9級(jí)特大地震影響洽胶,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜裆馒,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,025評(píng)論 3 334
  • 文/蒙蒙 一姊氓、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧领追,春花似錦他膳、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春蟀俊,著一層夾襖步出監(jiān)牢的瞬間钦铺,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工肢预, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留矛洞,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,081評(píng)論 3 377
  • 正文 我出身青樓烫映,卻偏偏與公主長(zhǎng)得像沼本,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子锭沟,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,675評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容