SDWebImage源代碼解析(一)Cache

前言

CSDN地址:http://blog.csdn.net/game3108/article/details/52575740
本文的中文注釋代碼demo更新在我的github上娱据。

SDWebImage是一個十分有名的Objective-C第三方開源框架腌闯,作用是:

Asynchronous image downloader with cache support as a UIImageView category

一個異步的圖片下載與緩存的UIImageViewCategory军拟。

本文也將對SDWebImage的源代碼進行一次簡單的解析滥玷,當(dāng)作學(xué)習(xí)和記錄休讳。
SDWebImage源代碼較長,本文會分為一個一個部分進行解析洛心。本次解析的部分就是SDImageCache欧瘪。

SDImageCache使用

SDWebImage的使用十分簡單囚衔,比較常用的一個接口:

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

只需要一個url和一個placeholderimage挖腰,就可以下載圖片和設(shè)置占位圖。

整體結(jié)構(gòu)

SDWebImage整體項目結(jié)構(gòu)圖:

SDWebImage

主要分為以下幾塊:
1.頭文件佳魔、宏定義曙聂、cancel接口
2.Downloader:下載圖片
3.Cache:圖片緩存
4.Utils:
SDWebImageManager:管理類
SDWebImageDecoder:圖片解壓縮類
SDWebImagePrefetcher:圖片預(yù)加載類
5.Categories:相關(guān)類使用接口

Cache

SDImageCache是用來緩存圖片到內(nèi)存以及硬盤,它主要包含以下幾類方法:

  • 創(chuàng)建Cache空間和路徑
  • 存儲圖片
  • 讀取圖片
  • 刪除圖片
  • 刪除緩存
  • 清理緩存
  • 獲取硬盤緩存大小
  • 判斷key是否存在在硬盤

創(chuàng)建Cache空間和路徑

SDImageCache的初始化方法就是初始化一些基本的值和注冊相關(guān)的notification鞠鲜。
相關(guān)方法如下:

//單例
+ (SDImageCache *)sharedImageCache;
//初始化一個namespace空間
- (id)initWithNamespace:(NSString *)ns;
//初始化一個namespace空間和存儲的路徑
- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory;
//存儲路徑
-(NSString *)makeDiskCachePath:(NSString*)fullNamespace;
//添加只讀cache的path
- (void)addReadOnlyCachePath:(NSString *)path;

實現(xiàn)如下:

//標(biāo)準(zhǔn)單例創(chuàng)建方法
+ (SDImageCache *)sharedImageCache {
    static dispatch_once_t once;
    static id instance;
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}

//添加只讀的cachePath
- (void)addReadOnlyCachePath:(NSString *)path {
    //只讀路徑宁脊,只在查找圖片時候使用
    if (!self.customPaths) {
        self.customPaths = [NSMutableArray new];
    }

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

//初始化默認方法
- (id)init {
    return [self initWithNamespace:@"default"];
}

- (id)initWithNamespace:(NSString *)ns {
    //獲取路徑,再初始化
    NSString *path = [self makeDiskCachePath:ns];
    return [self initWithNamespace:ns diskCacheDirectory:path];
}

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

        // initialise PNG signature data
        //初始化PNG圖片的標(biāo)簽數(shù)據(jù)
        kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8];

        // Create IO serial queue
        //創(chuàng)建 serial queue
        _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);

        // Init default values
        //默認存儲時間一周
        _maxCacheAge = kDefaultCacheMaxCacheAge;

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

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

        // Set decompression to YES
        //需要壓縮圖片
        _shouldDecompressImages = YES;

        // memory cache enabled
        //需要cache在內(nèi)存
        _shouldCacheImagesInMemory = YES;

        // Disable iCloud
        //禁止icloud
        _shouldDisableiCloud = YES;

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

#if TARGET_OS_IOS
        // Subscribe to app events
        //app相關(guān)warning贤姆,包括內(nèi)存warning榆苞,app關(guān)閉notification,到后臺notification
        [[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;
}

其中需要說一下的是kPNGSignatureData霞捡,它是用來判斷是否是PNG圖片的前綴標(biāo)簽數(shù)據(jù)坐漏,它的初始化數(shù)據(jù)kPNGSignatureBytes的來源如下:

// PNG圖片的標(biāo)簽值
static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};

存儲圖片

存儲圖片主要分為2塊:

  • 存儲到內(nèi)存
    直接計算圖片大小后,用NSCache *memCache存儲
  • 存儲到硬盤
    先將UIImage轉(zhuǎn)為NSData碧信,然后通過NSFileManager *_fileManager創(chuàng)建存儲路徑文件夾和圖片存儲文件

相關(guān)方法如下:

//存儲image到key
- (void)storeImage:(UIImage *)image forKey:(NSString *)key;

//存儲image到key赊琳,是否硬盤緩存
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;

//存儲image,是否重新計算圖片砰碴,服務(wù)器的數(shù)據(jù)來源躏筏,key,是否硬盤緩存
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;

//硬盤緩存呈枉,key
- (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)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];
}

//存儲到硬盤
- (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key {
    
    //沒有圖片返回
    if (!imageData) {
        return;
    }
    
    //判斷是否存在硬盤存儲的文件夾
    if (![_fileManager fileExistsAtPath:_diskCachePath]) {
        //沒有澤創(chuàng)建
        [_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
    //金庸icloud
    if (self.shouldDisableiCloud) {
        [fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
}

//存儲圖片基礎(chǔ)方法
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk {
    if (!image || !key) {
        return;
    }
    // if memory cache is enabled
    //是否緩存在內(nèi)存中國年
    if (self.shouldCacheImagesInMemory) {
        //獲取圖片大小
        NSUInteger cost = SDCacheCostForImage(image);
        //設(shè)置緩存
        [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

                // 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
                int alphaInfo = CGImageGetAlphaInfo(image.CGImage);
                //判斷是否有alpha
                BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone ||
                                  alphaInfo == kCGImageAlphaNoneSkipFirst ||
                                  alphaInfo == kCGImageAlphaNoneSkipLast);
                //有alpha肯定是png
                BOOL imageIsPng = hasAlpha;

                // But if we have an image data, we will look at the preffix
                //查看圖片前幾個字節(jié)趁尼,是否是png
                if ([imageData length] >= [kPNGSignatureData length]) {
                    imageIsPng = ImageDataHasPNGPreffix(imageData);
                }

                //png圖
                if (imageIsPng) {
                    data = UIImagePNGRepresentation(image);
                }
                //jpeg圖
                else {
                    data = UIImageJPEGRepresentation(image, (CGFloat)1.0);
                }
#else
                data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil];
#endif
            }
            //存儲到硬盤
            [self storeImageDataToDisk:data forKey:key];
        });
    }
}

其中對于獲取key的完整路徑處理NSString *cachePathForKey = [self defaultCachePathForKey:key];,還做了md5的加密猖辫,具體實現(xiàn)如下:

//path組合key
- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path {
    NSString *filename = [self cachedFileNameForKey:key];
    return [path stringByAppendingPathComponent:filename];
}

//默認路徑的keypath
- (NSString *)defaultCachePathForKey:(NSString *)key {
    return [self cachePathForKey:key inPath:self.diskCachePath];
}

#pragma mark SDImageCache (private)

//MD5加密key
- (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;
}

讀取圖片

讀取圖片主要分為兩步:

  • 內(nèi)存cache讀取
    直接讀取內(nèi)存cacheself.memCache
  • 硬盤圖片讀取
    先從內(nèi)存讀取cache酥泞,如果不存在,則從硬盤讀取啃憎,并且有必要的情況下存儲到內(nèi)存cache中

相關(guān)方法如下:

//cache存儲位置enum
typedef NS_ENUM(NSInteger, SDImageCacheType) {
    /**
     * The image wasn't available the SDWebImage caches, but was downloaded from the web.
     */
    SDImageCacheTypeNone,
    /**
     * The image was obtained from the disk cache.
     */
    SDImageCacheTypeDisk,
    /**
     * The image was obtained from the memory cache.
     */
    SDImageCacheTypeMemory
};

//3個cache block
typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType);

//異步請求緩存圖片芝囤,通過block
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;

//直接讀取cache的圖片
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;

//通過key,直接讀取硬盤
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
//內(nèi)存直接讀取image
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key {
    return [self.memCache objectForKey:key];
}

//硬盤直接讀取image
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key {

    // First check the in-memory cache...
    //先檢查內(nèi)存中是否含有
    UIImage *image = [self imageFromMemoryCacheForKey:key];
    if (image) {
        return image;
    }

    // Second check the disk cache...
    //獲取硬盤存儲的image
    UIImage *diskImage = [self diskImageForKey:key];
    //如果獲取到了,并且需要存儲到內(nèi)存cache
    if (diskImage && self.shouldCacheImagesInMemory) {
        //存儲到cache
        NSUInteger cost = SDCacheCostForImage(diskImage);
        [self.memCache setObject:diskImage forKey:key cost:cost];
    }

    return diskImage;
}
//異步獲取圖片
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
    if (!doneBlock) {
        return nil;
    }
    
    //沒有key凡人,則返回不存在
    if (!key) {
        doneBlock(nil, SDImageCacheTypeNone);
        return nil;
    }

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

    NSOperation *operation = [NSOperation new];
    //硬盤查找速度較慢名党,在子線程中查找
    dispatch_async(self.ioQueue, ^{
        if (operation.isCancelled) {
            return;
        }
        //創(chuàng)建autoreleasepool
        @autoreleasepool {
            //獲取硬盤圖片
            UIImage *diskImage = [self diskImageForKey:key];
            //如果獲取到了,并且需要存儲到內(nèi)存cache
            if (diskImage && self.shouldCacheImagesInMemory) {
                //獲得大小并存儲圖片
                NSUInteger cost = SDCacheCostForImage(diskImage);
                [self.memCache setObject:diskImage forKey:key cost:cost];
            }
            //回到主線程返回結(jié)果
            dispatch_async(dispatch_get_main_queue(), ^{
                doneBlock(diskImage, SDImageCacheTypeDisk);
            });
        }
    });

    return operation;
}

其中挠轴,對于從硬盤存儲獲取圖片UIImage *diskImage = [self diskImageForKey:key];的實現(xiàn)如下:

//硬盤返回圖片
- (UIImage *)diskImageForKey:(NSString *)key {
    //搜索所有的path,然后把這個key的圖片拿出來
    NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
    //如果有data
    if (data) {
        //data轉(zhuǎn)為image耳幢,實現(xiàn)在UIImage+MultiFormat中
        UIImage *image = [UIImage sd_imageWithData:data];
        //圖片適配屏幕
        image = [self scaledImageForKey:key image:image];
        //壓縮圖片岸晦,實現(xiàn)在SDWebImageDecoder
        if (self.shouldDecompressImages) {
            image = [UIImage decodedImageWithImage:image];
        }
        return image;
    }
    else {
        return nil;
    }
}

//適配屏幕
- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
    //方法在SDWebImageCompat中
    return SDScaledImageForKey(key, image);
}

//從所有path中讀取圖片
- (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
    //去掉path extension,這塊應(yīng)該是為了兼容某一個版本添加的path extension睛藻,所以本質(zhì)上是個兼容舊版本的邏輯判斷
    data = [NSData dataWithContentsOfFile:[defaultPath stringByDeletingPathExtension]];
    if (data) {
        return data;
    }

    //本地只讀路徑讀取
    NSArray *customPaths = [self.customPaths copy];
    for (NSString *path in customPaths) {
        //獲取只讀路徑中的filepath
        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;
}

這邊牽扯到好幾個其他類的方法启上,這邊就不先標(biāo)注它們的源代碼了,等到講到的時候再講一下店印。

刪除圖片

刪除圖片方法分為兩步:

  • 先從cache刪除緩存圖片
  • 然后硬盤刪除對應(yīng)文件

相關(guān)方法如下:

//通過key冈在,刪除圖片
- (void)removeImageForKey:(NSString *)key;

//異步刪除圖片,調(diào)用完成block
- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;

//刪除圖片按摘,同時從硬盤刪除
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;

//異步刪除包券,同時刪除硬盤
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
//刪除圖片
- (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];
}

//刪除圖片基礎(chǔ)方法
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion {
    
    //不存在key返回
    if (key == nil) {
        return;
    }

    //需要用memory,先從cache刪除圖片
    if (self.shouldCacheImagesInMemory) {
        [self.memCache removeObjectForKey:key];
    }
    
    //硬盤刪除
    if (fromDisk) {
        dispatch_async(self.ioQueue, ^{
            //直接刪除路徑下key對應(yīng)的文件名字
            [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
            
            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion();
                });
            }
        });
    } else if (completion){
        completion();
    }
    
}

刪除緩存

刪除緩存也分為兩塊:

  • 直接清空緩存memCache
  • 刪除硬盤存儲目錄炫贤,再重新創(chuàng)建目錄

相關(guān)方法

//刪除緩存圖片
- (void)clearMemory;

//刪除硬盤存儲圖片溅固,調(diào)用完成block
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;

//刪除硬盤存儲圖片
- (void)clearDisk;
//輕松memcache
- (void)clearMemory {
    [self.memCache removeAllObjects];
}

//刪除硬盤存儲
- (void)clearDisk {
    [self clearDiskOnCompletion:nil];
}

//刪除硬盤存儲基礎(chǔ)方法
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion
{
    dispatch_async(self.ioQueue, ^{
        //直接刪除存文件的路徑
        [_fileManager removeItemAtPath:self.diskCachePath error:nil];
        //重新創(chuàng)建文件路徑
        [_fileManager createDirectoryAtPath:self.diskCachePath
                withIntermediateDirectories:YES
                                 attributes:nil
                                      error:NULL];

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

清理緩存

清理緩存的目標(biāo)是將過期的圖片和確保硬盤存儲大小小于最大存儲許可。
清理緩存的方法也是分為兩步:

  • 清除所有過期圖片
  • 在硬盤存儲大小大于最大存儲許可大小時兰珍,將舊圖片進行刪除侍郭,刪除到一半最大許可以下

相關(guān)方法:

//清理硬盤緩存圖片
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock;

//清理硬盤緩存圖片
- (void)cleanDisk;
//清理硬盤
- (void)cleanDisk {
    [self cleanDiskWithCompletionBlock:nil];
}

//清理硬盤基礎(chǔ)方法
//清理硬盤的目的是為了緩解硬盤壓力,以及過期圖片掠河,超大小圖片等
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock {
    dispatch_async(self.ioQueue, ^{
        //硬盤存儲路徑獲取
        NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
        //是否是目錄亮元,獲取修改日期,獲取size大小
        NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];

        // This enumerator prefetches useful properties for our cache files.
        //迭代器遍歷
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
                                                   includingPropertiesForKeys:resourceKeys
                                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                 errorHandler:NULL];
        //獲取應(yīng)該過期的日期
        NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge];
        //緩存路徑與3個key值
        NSMutableDictionary *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.
        
        //需要刪除的路徑存儲
        NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init];
        //遍歷路徑下的所有文件于文件夾
        for (NSURL *fileURL in fileEnumerator) {
            //獲取該文件路徑的3種值
            NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL];

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

            // Remove files that are older than the expiration date;
            //獲取修改日期
            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.
            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)前硬盤存儲大于最大緩存爆捞,則刪除一半的硬盤存儲,先刪除老的圖片
        if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) {
            // Target half of our maximum cache size for this cleanup pass.
            
            //目標(biāo)空間
            const NSUInteger desiredCacheSize = self.maxCacheSize / 2;

            // Sort the remaining cache files by their last modification time (oldest first).
            
            //排序所有filepath跃闹,時間排序
            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.
            //刪除文件嵌削,直到小于目標(biāo)空間停止
            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;
                    }
                }
            }
        }
        //回調(diào)block
        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock();
            });
        }
    });
}

這邊需要提一下,當(dāng)app進入后臺望艺,發(fā)送notification苛秕,調(diào)用的方法,就是清理硬盤內(nèi)存找默,方法如下:

//后臺清理硬盤
- (void)backgroundCleanDisk {
    Class UIApplicationClass = NSClassFromString(@"UIApplication");
    if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
        return;
    }
    UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
    //設(shè)置后臺存活艇劫,在ios7以上最多存在3分鐘,7以下是10分鐘
    __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 cleanDiskWithCompletionBlock:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
}

獲取硬盤緩存大小

獲取硬盤緩存大小直接讀取硬盤路徑下的文件數(shù)量和每個文件大小惩激,進行累加店煞。
相關(guān)方法如下:

typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);
//獲得硬盤存儲空間大小
- (NSUInteger)getSize;

//獲得硬盤空間圖片數(shù)量
- (NSUInteger)getDiskCount;

//異步計算硬盤空間大小
- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock;
//獲取硬盤存儲的大小
- (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 *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
            //算大小
            size += [attrs fileSize];
        }
    });
    return size;
}

//獲取硬盤存儲的數(shù)量
- (NSUInteger)getDiskCount {
    __block NSUInteger count = 0;
    dispatch_sync(self.ioQueue, ^{
        //硬盤路徑迭代器
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        count = [[fileEnumerator allObjects] count];
    });
    return count;
}

//異步獲取硬盤緩存大小
- (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;
            //獲取size
            [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
            totalSize += [fileSize unsignedIntegerValue];
            fileCount += 1;
        }

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

判斷key是否存在在硬盤

判斷key是否存在在硬盤中蟹演,直接從硬盤中判斷是否存在此key的文件路徑
相關(guān)方法如下:

typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache);
//異步判斷是否存在key的圖片
- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;

//同步判斷是否存在key的圖片
- (BOOL)diskImageExistsWithKey:(NSString *)key;
//直接讀取
- (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
    // checking the key with and without the extension
    if (!exists) {
        exists = [[NSFileManager defaultManager] fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
    }
    
    return exists;
}

//判斷是否有key的文件
- (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
        
        //不存在去讀區(qū)去掉path extension的方式
        if (!exists) {
            exists = [_fileManager fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
        }
        
        //回調(diào)block
        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(exists);
            });
        }
    });
}

總結(jié)

SDWebImage本身牽扯到很多內(nèi)容,這篇文章先整體講了一下SDImageCache的設(shè)計與實現(xiàn)顷蟀,它有如下優(yōu)點:

  • 1.memory的cache和硬盤存儲結(jié)合存儲
  • 2.后臺清理硬盤存儲空間
  • 3.NSURL的文件讀取用途和相關(guān)文件夾迭代器和獲取
  • 4.精妙的kPNGSignatureData判斷是否是PNG圖片
  • 5.分別提供同步和異步的方法

當(dāng)然也有一個path extension文件名問題酒请。
這也告訴我們一個道理选脊,很多時候文件名一定要想好怎么去存儲逆济,一旦進行修改了,后續(xù)兼容會很麻煩腿倚。

其他

本來是想SDWebImage解析完后與YYWebImage對比一下的囤萤,但既然都已經(jīng)分文章去單獨寫了SDImageCache了昼窗,下篇文章就先解析YYCache


看了看YYCache的源代碼涛舍,確實比較長澄惊,還是先把SDWebImage分析完。

參考資料

1.Avoiding Image Decompression Sickness
2.SDWebImage源碼淺析

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末富雅,一起剝皮案震驚了整個濱河市掸驱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌吹榴,老刑警劉巖亭敢,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異图筹,居然都是意外死亡帅刀,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門远剩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來扣溺,“玉大人,你說我怎么就攤上這事瓜晤∽队啵” “怎么了?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵痢掠,是天一觀的道長驱犹。 經(jīng)常有香客問我,道長足画,這世上最難降的妖魔是什么雄驹? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮淹辞,結(jié)果婚禮上医舆,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好蔬将,可當(dāng)我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布爷速。 她就那樣靜靜地躺著,像睡著了一般霞怀。 火紅的嫁衣襯著肌膚如雪惫东。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天里烦,我揣著相機與錄音凿蒜,去河邊找鬼。 笑死胁黑,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的州泊。 我是一名探鬼主播丧蘸,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼遥皂!你這毒婦竟也來了力喷?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤演训,失蹤者是張志新(化名)和其女友劉穎弟孟,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體样悟,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡拂募,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了窟她。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片陈症。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖震糖,靈堂內(nèi)的尸體忽然破棺而出录肯,到底是詐尸還是另有隱情,我是刑警寧澤吊说,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布论咏,位于F島的核電站,受9級特大地震影響颁井,放射性物質(zhì)發(fā)生泄漏厅贪。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一蚤蔓、第九天 我趴在偏房一處隱蔽的房頂上張望卦溢。 院中可真熱鬧,春花似錦、人聲如沸单寂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽宣决。三九已至蘸劈,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間尊沸,已是汗流浹背威沫。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留洼专,地道東北人棒掠。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像屁商,于是被迫代替她去往敵國和親烟很。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,577評論 2 353

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