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