SDWebImage原始碼解析(三)

huang303513發表於2017-05-03

1 概述

這篇博文中,我將分析SDWebImageManagerSDImageCacheSDWebImageManager擁有一個SDWebImageCacheSDWebImageDownloader屬性分別用於圖片的快取和載入處理。為UIView及其子類提供了載入圖片的統一介面。管理正在載入操作的集合,這個類是一個單列。同時管理各種載入選項的處理。SDImageCache負責SDWebImage的整個快取工作,是一個單列物件。快取路徑處理、快取名字處理、管理記憶體快取和磁碟快取的建立和刪除、根據指定key獲取圖片、存入圖片的型別處理、根據快取的建立和修改日期刪除快取。

2 SDWebImageManager分析

UIImageView等各種檢視通過UIView+WebCache分類的sd_internalSetImageWithURL方法來呼叫SDWebImageManager類的如下方法實現圖片載入:

/**
 這個方法是核心方法。UIImageView等這種分類都預設通過呼叫這個方法來獲取資料。

 @param url 圖片的url地址
 @param options 獲取圖片的屬性
 @param progressBlock 載入進度回撥
 @param completedBlock 載入完成回撥
 @return 返回一個載入的載體物件。以便提供給後面取消刪除等。
 */
- (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
                                              options:(SDWebImageOptions)options
                                             progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                            completed:(nullable SDInternalCompletionBlock)completedBlock;

首先看他地第二個引數options。這個引數指定了圖片載入過程中的不同選項。指定不同選項,SDWebImage可以根據選項做不同的處理,這是一個列舉型別,多個選項之間可以組合使用。

/**
 列舉,定義了圖片載入處理過程中的選項
 */
typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
    /*
     預設情況下,當一個URL下載失敗的時候,這個URL會被加入黑名單列表,下次再有這個url的請求則停止請求。
     如果為true,這個值表示需要再嘗試請求。
     */
    SDWebImageRetryFailed = 1 << 0,

    /*
     預設情況下,當UI可以互動的時候就開始載入圖片。這個標記可以阻止這個時候載入。
     而是當UIScrollView開始減速滑動的時候開始載入。
     */
    SDWebImageLowPriority = 1 << 1,

    /*
     這個屬性禁止磁碟快取
     */
    SDWebImageCacheMemoryOnly = 1 << 2,

    /*
     這個標記允許圖片在載入過程中顯示,就像瀏覽器那樣。
     預設情況下,圖片只會在載入完成以後再顯示。
     */
    SDWebImageProgressiveDownload = 1 << 3,

    /*
     *即使本地已經快取了圖片,但是根據HTTP的快取策略去網路上載入圖片。也就是說本地快取了也不管了,嘗試從網路上載入資料。但是具體是從代理載入、HTTP快取載入、還是原始伺服器載入這個就更具HTTP的請求頭配置。
     *使用NSURLCache而不是SDWebImage來處理磁碟快取。從而可能會導致輕微的效能損害。
     *這個選項專門用於處理,url地址沒有變,但是url對於的圖片資料在伺服器改變的情況。
     *如果一個快取圖片更新了,則completion這個回撥會被呼叫兩次,一次返回快取圖片,一次返回最終圖片。
     *我們只有在不能確保URL和他對應的內容不能完全對應的時候才使用這個標記。
     */
    SDWebImageRefreshCached = 1 << 4,

    /*
     當應用進入後臺以後,圖片繼續下載。應用進入後臺以後,通過向系統申請額外的時間來完成。如果時間超時,那麼下載操作會被取消。
     */
    SDWebImageContinueInBackground = 1 << 5,

    /*
     處理快取在`NSHTTPCookieStore`物件裡面的cookie。通過設定`NSMutableURLRequest.HTTPShouldHandleCookies = YES`來實現的。
     */
    SDWebImageHandleCookies = 1 << 6,

    /*
     *允許非信任的SSL證書請求。
     *在測試的時候很有用。但是正式環境要小心使用。
     */
    SDWebImageAllowInvalidSSLCertificates = 1 << 7,

    /*
     * 預設情況下,圖片載入的順序是根據加入佇列的順序載入的。但是這個標記會把任務加入佇列的最前面。
     */
    SDWebImageHighPriority = 1 << 8,
    
    /*
     預設情況下,在圖片載入的過程中,會顯示佔點陣圖。
     但是這個標記會阻止顯示佔點陣圖直到圖片載入完成。
     */
    SDWebImageDelayPlaceholder = 1 << 9,

    /*
     *預設情況下,我們不會去呼叫`animated images`(估計就是多張圖片迴圈顯示或者GIF圖片)的`transformDownloadedImage`代理方法來處理圖片。因為大部分transformation操作會對圖片做無用處理。
     *用這個標記表示無論如何都要對圖片做transform處理。
     */
    SDWebImageTransformAnimatedImage = 1 << 10,
    
    /*
     *預設情況下,圖片再下載完成以後都會被自動載入到UIImageView物件上面。但是有時我們希望UIImageView載入我們手動處理以後的圖片。
     *這個標記允許我們在completion這個Block中手動設定處理好以後的圖片。
     */
    SDWebImageAvoidAutoSetImage = 1 << 11,
    
    /*
     *預設情況下,圖片會按照他的原始大小來解碼顯示。根據裝置的記憶體限制,這個屬性會調整圖片的尺寸到合適的大小再解壓縮。
     *如果`SDWebImageProgressiveDownload`標記被設定了,則這個flag不起作用。
     */
    SDWebImageScaleDownLargeImages = 1 << 12
};

接下來我先看SDWebImageManager的初始化過程。

- (nonnull instancetype)init {
    SDImageCache *cache = [SDImageCache sharedImageCache];
    SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
    return [self initWithCache:cache downloader:downloader];
}

/**
 初始化SDImageCache和SDWebImageDownloader物件

 @param cache SDImageCache物件
 @param downloader SDWebImageDownloader物件
 @return 返回初始化結果
 */
- (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader {
    if ((self = [super init])) {
        _imageCache = cache;
        _imageDownloader = downloader;
        //用於儲存載入失敗的url集合
        _failedURLs = [NSMutableSet new];
        //用於儲存當前正在載入的Operation
        _runningOperations = [NSMutableArray new];
    }
    return self;
}

loadImageWithURL方法是SDWebImageManager最核心的方法,實現過程:

/**
 這個方法是核心方法。UIImageView等這種分類都預設通過呼叫這個方法來獲取資料。

 @param url 圖片的url地址
 @param options 獲取圖片的屬性
 @param progressBlock 載入進度回撥
 @param completedBlock 載入完成回撥
 @return 返回一個載入的載體物件。以便提供給後面取消刪除等。
 */
- (id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
                                     options:(SDWebImageOptions)options
                                    progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                   completed:(nullable SDInternalCompletionBlock)completedBlock {
    /*
     如果傳入的url是NSString格式的。則轉換為NSURL型別再處理
     */
    if ([url isKindOfClass:NSString.class]) {
        url = [NSURL URLWithString:(NSString *)url];
    }

    // Prevents app crashing on argument type error like sending NSNull instead of NSURL
    //如果url不會NSURL型別的物件。則置為nil
    if (![url isKindOfClass:NSURL.class]) {
        url = nil;
    }
    /*
     圖片載入獲取獲取過程中繫結一個`SDWebImageCombinedOperation`物件。以方便後續再通過這個物件對url的載入控制。
     */
    __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
    __weak SDWebImageCombinedOperation *weakOperation = operation;

    BOOL isFailedUrl = NO;
    //當前url是否在失敗url的集合裡面
    if (url) {
        @synchronized (self.failedURLs) {
            isFailedUrl = [self.failedURLs containsObject:url];
        }
    }
    /*
     如果url是失敗的url或者url有問題等各種問題。則直接根據opeation來做異常情況的處理
     */
    if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
        //構建回撥Block
        [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url];
        return operation;
    }
    //把載入圖片的一個載體存入runningOperations。裡面是所有正在做圖片載入過程的operation的集合。
    @synchronized (self.runningOperations) {
        [self.runningOperations addObject:operation];
    }
    //根據url獲取url對應的key
    NSString *key = [self cacheKeyForURL:url];
    /*
    *如果圖片是從記憶體載入,則返回的cacheOperation是nil,
    *如果是從磁碟載入,則返回的cacheOperation是`NSOperation`物件。
    *如果是從網路載入,則返回的cacheOperation物件是`SDWebImageDownloaderOperation`物件。
    */
    operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
        //從快取中獲取圖片資料返回
        //如果已經取消了操作。則直接返回並且移除對應的opetation物件
        if (operation.isCancelled) {
            [self safelyRemoveOperationFromRunning:operation];
            return;
        }
        
        if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
            /**
             如果從快取獲取圖片失敗。或者設定了SDWebImageRefreshCached來忽略快取。則先把快取的圖片返回。
             */
            if (cachedImage && options & SDWebImageRefreshCached) {
                //構建回撥Block
                [self callCompletionBlockForOperation:weakOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
            }

            // download if no image or requested to refresh anyway, and download allowed by delegate
            /*
             把圖片載入的`SDWebImageOptions`型別列舉轉換為圖片下載的`SDWebImageDownloaderOptions`型別的列舉
             */
            SDWebImageDownloaderOptions downloaderOptions = 0;
            if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
            if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload;
            if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache;
            if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
            if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
            if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
            if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority;
            if (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages;
            /*
             如果設定了強制重新整理快取的選項。則`SDWebImageDownloaderProgressiveDownload`選項失效並且新增`SDWebImageDownloaderIgnoreCachedResponse`選項。
             */
            if (cachedImage && options & SDWebImageRefreshCached) {
                // force progressive off if image already cached but forced refreshing
                downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
                // ignore image read from NSURLCache if image if cached but force refreshing
                downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
            }
            /*
             新建一個網路下載的操作。
             */
            SDWebImageDownloadToken *subOperationToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {
                __strong __typeof(weakOperation) strongOperation = weakOperation;
                //如果圖片下載結束以後,對應的圖片載入操作已經取消。則什麼處理都不做
                if (!strongOperation || strongOperation.isCancelled) {
                   //如果operation已經被取消了,則什麼也不做
                } else if (error) {
                    //如果載入出錯。則直接返回回撥。並且新增到failedURLs中
                    [self callCompletionBlockForOperation:strongOperation completion:completedBlock error:error url:url];

                    if (   error.code != NSURLErrorNotConnectedToInternet
                        && error.code != NSURLErrorCancelled
                        && error.code != NSURLErrorTimedOut
                        && error.code != NSURLErrorInternationalRoamingOff
                        && error.code != NSURLErrorDataNotAllowed
                        && error.code != NSURLErrorCannotFindHost
                        && error.code != NSURLErrorCannotConnectToHost
                        && error.code != NSURLErrorNetworkConnectionLost) {
                        @synchronized (self.failedURLs) {
                            [self.failedURLs addObject:url];
                        }
                    }
                }
                else {
                    //網路圖片載入成功
                    if ((options & SDWebImageRetryFailed)) {
                        //如果有重試失敗下載的選項。則把url從failedURLS中移除
                        @synchronized (self.failedURLs) {
                            [self.failedURLs removeObject:url];
                        }
                    }
                    
                    BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);

                    if (options & SDWebImageRefreshCached && cachedImage && !downloadedImage) {
                        // Image refresh hit the NSURLCache cache, do not call the completion block
                        //如果成功下載圖片。並且圖片是動態圖片。並且設定了SDWebImageTransformAnimatedImage屬性。則處理圖片
                    } else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                            //獲取transform以後的圖片
                            UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
                            //儲存transform以後的的圖片
                            if (transformedImage && finished) {
                                BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
                                // pass nil if the image was transformed, so we can recalculate the data from the image
                                [self.imageCache storeImage:transformedImage imageData:(imageWasTransformed ? nil : downloadedData) forKey:key toDisk:cacheOnDisk completion:nil];
                            }
                            //回撥拼接
                            [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
                        });
                    } else {
                        //如果成功下載圖片。並且圖片不是圖片。則直接快取和回撥
                        if (downloadedImage && finished) {
                            [self.imageCache storeImage:downloadedImage imageData:downloadedData forKey:key toDisk:cacheOnDisk completion:nil];
                        }
                        //回撥拼接
                        [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:downloadedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
                    }
                }
                //從正在載入的圖片操作集合中移除當前操作
                if (finished) {
                    [self safelyRemoveOperationFromRunning:strongOperation];
                }
            }];
            //重置cancelBlock,取消下載operation
            operation.cancelBlock = ^{
                [self.imageDownloader cancel:subOperationToken];
                __strong __typeof(weakOperation) strongOperation = weakOperation;
                [self safelyRemoveOperationFromRunning:strongOperation];
            };
        } else if (cachedImage) {
            //如果獲取到了快取圖片。在直接通過快取圖片處理
            __strong __typeof(weakOperation) strongOperation = weakOperation;
            [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
            [self safelyRemoveOperationFromRunning:operation];
        } else {
            // Image not in cache and download disallowed by delegate
            //圖片麼有快取、並且圖片也沒有下載
            __strong __typeof(weakOperation) strongOperation = weakOperation;
            [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url];
            [self safelyRemoveOperationFromRunning:operation];
        }
    }];

    return operation;
}

通過對這個方法的分析,他主要實現的功能有:

  • 建立一個SDWebImageCombinedOperation物件,呼叫者可以通過這個物件來對載入做取消等操作。這個物件的cancelOperation屬性有如下幾種情況。

    • 如果圖片是從記憶體載入,則返回的cacheOperation是nil。

    • 如果是從磁碟載入,則返回的cacheOperation是NSOperation物件。

    • 如果是從網路載入,則返回的cacheOperation物件是SDWebImageDownloaderOperation物件。

  • 通過failedURLs屬性來儲存載入失敗的url。通過它可以阻止失敗的url再次載入,提高使用者體驗。

  • 通過runningOperations屬性記錄當前正在載入的Operation列表。

  • 載入結束以後,通過callCompletionBlockForOperation方法來拼接回撥Block。

  • SDWebImageOptions型別的列舉值轉換為SDWebImageDownloaderOptions型別的列舉值。

  • 圖片成功從網路載入以後,通過imageCache屬性的storeImage方法來快取圖片。

另外還有一些輔助性的方法,用於處理快取判斷、url與key轉換等功能:

/**
 根據url獲取url對應的快取key。
 如果有實現指定的url轉換key的Block,則用這個方式轉換為key。
 否則直接用url的絕對值多為key

 @param url url
 @return 快取的key
 */
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
    if (!url) {
        return @"";
    }
    if (self.cacheKeyFilter) {
        return self.cacheKeyFilter(url);
    } else {
        return url.absoluteString;
    }
}

/**
 一個url的快取是否存在

 @param url 快取資料對應的url
 @param completionBlock 快取結果回撥
 */
- (void)cachedImageExistsForURL:(nullable NSURL *)url
                     completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
    NSString *key = [self cacheKeyForURL:url];
    //記憶體裡面是否有key的快取
    BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil);
    //記憶體快取
    if (isInMemoryCache) {
        // making sure we call the completion block on the main queue
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionBlock) {
                completionBlock(YES);
            }
        });
        return;
    }
    //磁碟快取
    [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
        // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
        if (completionBlock) {
            completionBlock(isInDiskCache);
        }
    }];
}

/**
 url是否有磁碟快取資料

 @param url url
 @param completionBlock 回撥
 */
- (void)diskImageExistsForURL:(nullable NSURL *)url
                   completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
    NSString *key = [self cacheKeyForURL:url];
    
    [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
        // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
        if (completionBlock) {
            completionBlock(isInDiskCache);
        }
    }];
}

2.1 SDWebImageCombinedOperation分析

從上面的方法,發現loadImageWithURL方法會返回一個SDWebImageCombinedOperation給呼叫者,這個物件有個cancel方法,這個方法繼承自SDWebImageOperation協議。方法裡面會呼叫SDWebImageDownlaoderOperation或者NSOperation的cancel方法

/**
 通過這個物件關聯一個`SDWebImageDownloaderOperation`物件
 */
@interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>

/**
 用於判斷Operation是否已經取消
 */
@property (assign, nonatomic, getter = isCancelled) BOOL cancelled;

/**
 取消回撥
 */
@property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock;

/**
 SDWebImageDownloaderOperation物件。可以通過這個屬性取消一個NSOperation
 */
@property (strong, nonatomic, nullable) NSOperation *cacheOperation;

@end

@implementation SDWebImageCombinedOperation

/**
 取消Operation的回撥Block

 @param cancelBlock 回撥Block
 */
- (void)setCancelBlock:(nullable SDWebImageNoParamsBlock)cancelBlock {
    // check if the operation is already cancelled, then we just call the cancelBlock
    if (self.isCancelled) {
        if (cancelBlock) {
            cancelBlock();
        }
        _cancelBlock = nil; // don`t forget to nil the cancelBlock, otherwise we will get crashes
    } else {
        _cancelBlock = [cancelBlock copy];
    }
}

/**
 呼叫cancel方法。這個方法繼承自`SDWebImageOperation`協議。方法裡面會呼叫`SDWebImageDownlaoderOperation`或者`NSOperation`的cancel方法
 */
- (void)cancel {
    self.cancelled = YES;
    if (self.cacheOperation) {
        //呼叫`SDWebImageDownlaoderOperation`或者`NSOperation`的cancel方法
        [self.cacheOperation cancel];
        self.cacheOperation = nil;
    }
    if (self.cancelBlock) {
        self.cancelBlock();
        
        // TODO: this is a temporary fix to #809.
        // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
        //        self.cancelBlock = nil;
        _cancelBlock = nil;
    }
}

@end

那麼取消一個Operation是在哪裡呢?其實就在UIView+WebCache中,所有使用SDWebImage的View都可以使用這個方法來取消下載Operation:

/**
 取消當前Class對應的所有載入請求
 */
- (void)sd_cancelCurrentImageLoad {
    [self sd_cancelImageLoadOperationWithKey:NSStringFromClass([self class])];
}

上面這個方法又會呼叫UIView+WebCacheOperation分類的sd_cancelImageLoadOperationWithKey方法來實現,這個方法會呼叫SDWebImageCombinedOperation物件的cancel方法,然後在cancel方法中再呼叫SDWebImageDownloadOperation或者NSOperationcancel方法:

/**
 取消當前key對應的所有`SDWebImageCombinedOperation`物件

 @param key Operation對應的key
 */
- (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key {
    // Cancel in progress downloader from queue
    //獲取當前View對應的所有key
    SDOperationsDictionary *operationDictionary = [self operationDictionary];
    //獲取對應的圖片載入Operation
    id operations = operationDictionary[key];
    //取消所有當前View對應的所有Operation
    if (operations) {
        if ([operations isKindOfClass:[NSArray class]]) {
            for (id <SDWebImageOperation> operation in operations) {
                if (operation) {
                    //SDWebImageCombinedOperation物件的cancel方法
                    [operation cancel];
                }
            }
        } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
            [(id<SDWebImageOperation>) operations cancel];
        }
        [operationDictionary removeObjectForKey:key];
    }
}

3 SDImageCache分析

從上面的程式碼中,發現SDWebImageManager通過SDImageCache來獲取/儲存圖片,而且SDImageCache是一個單列物件。他的具體實現可以總結為如下幾點:

  • 通過AutoPurgeCache這個NSCache子類來管理記憶體快取。當接收到記憶體警告的時候,移除記憶體快取的所有物件。

  • 接收到UIApplicationDidReceiveMemoryWarningNotification通知以後,會刪除記憶體中快取的圖片。

  • 接收到UIApplicationWillTerminateNotification通知以後,會通過deleteOldFiles方法刪除老的圖片。具體刪除規則如下:

    • 快取大小、過期日期、是否解壓縮快取、是否允許記憶體快取都是通過SDImageCacheConfig這個物件來配置的。

    • 首先會迭代快取目錄下的所有檔案,對於大於一週的圖片資料全部刪除。

    • 然後會記錄快取目錄的所有大小,如果當前快取大於預設快取,則按照建立日期開始刪除圖片快取,直到快取大小小於預設快取大小。

  • 當接收到UIApplicationDidEnterBackgroundNotification通知以後,會呼叫deleteOldFilesWithCompletionBlock來清理快取資料。

  • 定義了一些列方法來處理圖片的獲取、快取、移除操作。主要有下面幾個方法:

    • queryCacheOperationForKey查詢指定key對應的快取圖片,先從記憶體查詢,然後從磁碟查詢。

    • removeImageForKey移除指定的快取圖片。

    • diskImageDataBySearchingAllPathsForKey在磁碟上查詢指定key對應的圖片。

    • storeImageDataToDisk把指定的圖片資料存入磁碟。

  • 通過cachedFileNameForKey方法獲取一張圖片對應的MD5加密的快取名字。

SDImageCache的完整實現如下:

@interface AutoPurgeCache : NSCache
@end

/**
 如果接收到記憶體警告、移除所有的快取物件
 */
@implementation AutoPurgeCache

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

- (void)dealloc {
#if SD_UIKIT
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}

@end
/**
 計算一張圖片佔用記憶體的大小

 @param image 圖片
 @return 佔用記憶體大小
 */
FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
#if SD_MAC
    return image.size.height * image.size.width;
#elif SD_UIKIT || SD_WATCH
    return image.size.height * image.size.width * image.scale * image.scale;
#endif
}
/**
 單列物件、用處管理圖片的快取以及快取圖片的處理
 */
@interface SDImageCache ()

#pragma mark - Properties
@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;

@end

@implementation SDImageCache {
    NSFileManager *_fileManager;
}
#pragma mark - Singleton, init, dealloc
+ (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"];
}

- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns {
    NSString *path = [self makeDiskCachePath:ns];
    return [self initWithNamespace:ns diskCacheDirectory:path];
}

- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
                       diskCacheDirectory:(nonnull NSString *)directory {
    if ((self = [super init])) {
        NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
        // 初始化一個序列的dispatch_queue_t
        _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
        //初始化快取策略配置物件
        _config = [[SDImageCacheConfig alloc] init];
        
        // 初始化記憶體快取物件
        _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
        /*
         當應用收到記憶體警告的時候,清除記憶體快取。
         */
        [[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;
}

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

/**
 當前queue是否在ioQueue
 */
- (void)checkIfQueueIsIOQueue {
    const char *currentQueueLabel = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL);
    const char *ioQueueLabel = dispatch_queue_get_label(self.ioQueue);
    if (strcmp(currentQueueLabel, ioQueueLabel) != 0) {
        NSLog(@"This method should be called from the ioQueue");
    }
}

#pragma mark - Cache paths
/*
 新增只能讀的快取目錄
 */
- (void)addReadOnlyCachePath:(nonnull NSString *)path {
    if (!self.customPaths) {
        self.customPaths = [NSMutableArray new];
    }

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

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

 @param key 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加密
 X 表示以十六進位制形式輸出
 02 表示不足兩位,前面補0輸出;出過兩位,不影響

 @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 - 圖片快取具體實現的一些列方法

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

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

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

 @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 (self.config.shouldCacheImagesInMemory) {
        //計算快取資料的大小
        NSUInteger cost = SDCacheCostForImage(image);
        //加入快取對此昂
        [self.memCache setObject:image forKey:key cost:cost];
    }
    
    if (toDisk) {
        /*
         在一個線性佇列中做磁碟快取操作。
         */
        dispatch_async(self.ioQueue, ^{
            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) {
        //給檔案新增到執行儲存到iCloud屬性
        [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
}

#pragma mark - Query and Retrieve Ops

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

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

- (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的資料。通過一個NSOperation來完成

 @param key 要查詢的key
 @param doneBlock 查詢結束以後的Block
 @return 返回做查詢操作的Block
 */
- (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;
        //是否是gif圖片
        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;
}

#pragma mark - Remove Ops

- (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 - Mem Cache settings

- (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 - 記憶體快取清理相關操作

/**
 清理當前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

#pragma mark - Cache Info

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

- (NSUInteger)getDiskCount {
    __block NSUInteger count = 0;
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        count = fileEnumerator.allObjects.count;
    });
    return count;
}

- (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);
            });
        }
    });
}
@end

最後原文地址.html),demo地址

相關文章