SDWebImage 解析之 SDWebImageManager

Mar86T 8年前發布 | 9K 次閱讀 iOS開發 移動開發 SDWebImage

這里會做一些源碼的解析,也會對使用較多的類或方法進行簡單的介紹!

目前為止sdwebimage已經更新到4.0.0 測試的第二個版本,我們拿到源碼來看看。

只要修改源碼的同志們記得吃藥,大的架構永遠不會變。

一. SDWebImageManager (sdwebimage管理以及操作類)

我們先來看看SDWebImageManager.h文件中的內容

typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
/**
 * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.
 * This flag disable this blacklisting.
 *  如果選擇了這個flag,那么即使某個url下載失敗了,sdwebimage還是會嘗試再次下載他
 */
SDWebImageRetryFailed = 1 << 0,

/**
 * By default, image downloads are started during UI interactions, this flags disable this feature,
 * leading to delayed download on UIScrollView deceleration for instance.
 * 默認情況下,圖片會在交互發生的時候下載(例如你滑動tableview的時候),這個flag會禁止這個特性,導致的結果就是在scrollview減速的時候才會開始下載
 */
SDWebImageLowPriority = 1 << 1,

/**
 * This flag disables on-disk caching
 * 這個flag不支持磁盤緩存
 */
SDWebImageCacheMemoryOnly = 1 << 2,

/**
 * This flag enables progressive download, the image is displayed progressively during download as a browser would do.
 * By default, the image is only displayed once completely downloaded.
 * 這個flag會使圖片邊下載邊顯示,默認是下載完成再一次性顯示(就像你用瀏覽器瀏覽網頁的時候那種圖片下載,一截一截的顯示)
 */
SDWebImageProgressiveDownload = 1 << 3,

/**
 * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
 * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
 * This option helps deal with images changing behind the same request URL, e.g. 非死book graph api profile pics.
 * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.
 *
 * Use this flag only if you can't make your URLs static with embedded cache busting parameter.
 * 更換頭像的時候使用
 */
SDWebImageRefreshCached = 1 << 4,

/**
 * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
 * extra time in background to let the request finish. If the background task expires the operation will be cancelled.
 * 啟動后臺下載,加入你進入一個頁面,有一張圖片正在下載這時候你讓app進入后臺,圖片還是會繼續下載
 */
SDWebImageContinueInBackground = 1 << 5,

/**
 * Handles cookies stored in NSHTTPCookieStore by setting
 * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
 */
SDWebImageHandleCookies = 1 << 6,

/**
 * Enable to allow untrusted SSL certificates.
 * Useful for testing purposes. Use with caution in production.
 * 允許不安全的SSL證書,在正式環境中慎用
 */
SDWebImageAllowInvalidSSLCertificates = 1 << 7,

/**
 * By default, images are loaded in the order in which they were queued. This flag moves them to
 * the front of the queue.
 * 默認情況下,image在裝載的時候是按照他們在隊列中的順序裝載的(就是先進先出).這個flag會把他們移動到隊列的前端,并且立刻裝載而不是等到當前隊列裝載的時候再裝載
 */
SDWebImageHighPriority = 1 << 8,

/**
 * By default, placeholder images are loaded while the image is loading. This flag will delay the loading
 * of the placeholder image until after the image has finished loading.
 * 默認情況下,占位圖會在圖片下載的時候顯示.這個flag開啟會延遲占位圖顯示的時間,等到圖片下載完成之后才會顯示占位圖(有何意義?)
 */
SDWebImageDelayPlaceholder = 1 << 9,

/**
 * We usually don't call transformDownloadedImage delegate method on animated images,
 * as most transformation code would mangle it.
 * Use this flag to transform them anyway.
 * 我們通常不會在動畫圖像上調用transformDownloadedImage委托方法,因為大多數轉換代碼會對它進行轉換,使用此標志來轉換它們(沒用過,不做評論)
 */
SDWebImageTransformAnimatedImage = 1 << 10,

/**
 * By default, image is added to the imageView after download. But in some cases, we want to
 * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance)
 * Use this flag if you want to manually set the image in the completion when success
 * 下載完成后手動設置圖片,默認是下載完成后自動放到ImageView上
 */
SDWebImageAvoidAutoSetImage = 1 << 11,

/**
 * By default, images are decoded respecting their original size. On iOS, this flag will scale down the
 * images to a size compatible with the constrained memory of devices.
 * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated.
 * 默認情況下,圖像將根據其原始大小進行解碼。 在iOS上,此標志會將圖片縮小到與設備的受限內存兼容的大小。如果設置了“SDWebImageProgressiveDownload”標志,則會關閉縮小比例
 */
SDWebImageScaleDownLargeImages = 1 << 12
};

//四個參數的block(下面會對參數進行介紹)
typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL);
//六個參數的block(同上)
typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL);
//只有一個url參數,用于將url轉換成緩存需要的key
typedef NSString * _Nullable (^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable url);


@class SDWebImageManager;

@protocol SDWebImageManagerDelegate <NSObject>

@optional

/**
 * Controls which image should be downloaded when the image is not found in the cache.
 *
 * @param imageManager The current `SDWebImageManager`
 * @param imageURL     The url of the image to be downloaded
 *
 * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
 * 代理方法:用于控制當前圖片沒有在緩存中找到,是否去下載這張圖片(默認是yes)
 */
- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nullable NSURL *)imageURL;

/**
 * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
 * NOTE: This method is called from a global queue in order to not to block the main thread.
 *
 * @param imageManager The current `SDWebImageManager`
 * @param image        The image to transform
 * @param imageURL     The url of the image to transform
 *
 * @return The transformed image object.
 * 圖片下載完成后在存儲到內存或磁盤之前立即轉換這張圖片
 * 注意:這個方法是異步加載的,為了防止主線程堵塞
 */
 - (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable NSURL *)imageURL;

@end

/**
 * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes.
 * SDWebImageManager是UIImageView + WebCache類別后面的類,并且非常相似
 * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache).
 * 它是異步下載器(SDWebImageDownloader)與圖像緩存存儲(SDImageCache)的紐帶(ties)
 * You can use this class directly to benefit(效益,利益) from web image downloading with caching in another context than
 * a UIView.
 * 您可以直接(directly)使用這個類從在UIView之外的另一個上下文中使用緩存獲得Web圖像下載
 * 意思就是說:你可以直接使用下面的方法來實現獨立的下載圖片的功能(有緩存機制)
 * Here is a simple example of how to use SDWebImageManager:
 *
 * @code

SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager loadImageWithURL:imageURL
              options:0
             progress:nil
            completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                if (image) {
                    // do something with image
                }
            }];

 * @endcode
 */
@interface SDWebImageManager : NSObject

@property (weak, nonatomic, nullable) id<SDWebImageManagerDelegate> delegate;

@property (strong, nonatomic, readonly, nullable) SDImageCache *imageCache;
@property (strong, nonatomic, readonly, nullable) SDWebImageDownloader *imageDownloader;

/**
 * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can
 * be used to remove dynamic part of an image URL.
 * 這個緩存過濾器是每次SDWebImageManager需要將URL轉換為緩存密鑰時使用的塊。 這可用于動態的刪除圖片網址
 * The following example sets a filter in the application delegate that will remove any query-string from the
 * URL before to use it as a cache key:
 * 以下示例在應用程序委托中設置一個過濾器,該過濾器將在將其用作緩存鍵之前從URL中刪除任何查詢字符串
 * @code

[[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {
url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
return [url absoluteString];
}];

 * @endcode
 */
@property (nonatomic, copy, nullable)SDWebImageCacheKeyFilterBlock cacheKeyFilter;

/**
 * Returns global SDWebImageManager instance.
 *
 * @return SDWebImageManager shared instance
 * 
 */

//單例,返回SDWebImageManager對象
+ (nonnull instancetype)sharedManager;

/**
 * Allows to specify(提起,指定) instance of cache and image downloader used with image manager.
 * 允許指定與圖像管理器一起使用的緩存和圖像下載程序的實例
 * @return new instance of `SDWebImageManager` with specified cache and downloader.
 */

//根據SDImageCache與SDWebImageDownloader的對象來創建一個SDWebImageManager的實例
- (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader;

/**
 * Downloads the image at the given URL if not present in cache or return the cached version otherwise.
 * 緩存中有的話取換取,沒有的話根據url下載
 * @param url            The URL to the image
 * @param options        A mask to specify options to use for this request
 * @param progressBlock  A block called while image is downloading
 *                       @note the progress block is executed on a background queue
 * @param completedBlock A block called when operation has been completed.
 *
 *   This parameter is required.
 * 
 *   This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter.
 *   
 *   In case of error the image parameter is nil and the third parameter may contain an NSError.
 *
 *   The forth parameter is an `SDImageCacheType` enum indicating(表明、指示) if the image was retrieved(檢索、回收、糾正) from the local cache
 *   or from the memory cache or from the network.
 *
 *   The fith parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is
 *   
 *   downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the
 *   block is called a last time with the full image and the last parameter set to YES.
 *
 *   The last parameter is the original image URL
 *   此塊沒有返回值,并將所請求的UIImage作為第一個參數,將NSData表示作為第二個參數。
 *   如果出現錯誤,image參數為nil,第三個參數可能包含NSError
 *   第四個參數是一個“SDImageCacheType”枚舉,指示圖像是從本地緩存檢索的,還是從內存緩存或網絡檢索的
 *   當使用SDWebImageProgressiveDownload選項并且正在下載映像(圖片)時,fith參數設置為NO,因此此塊會使用部分映像重復調用(重復調用加載部分圖片直到加載全部)
 *   當圖像完全下載時,該塊被稱為最后一次,完整圖像和最后一個參數設置為YES。
 *   最后的參數是一個url地址
 *
 * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation
 */
- (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
                                          options:(SDWebImageOptions)options
                                         progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                        completed:(nullable SDInternalCompletionBlock)completedBlock;

/**
 * Saves image to cache for given URL
 *
 * @param image The image to cache
 * @param url   The URL to the image
 *
 */

//將圖片存入cache的方法,類似于字典的setValue: forKey:
- (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url;

/**
 * Cancel all current operations
 */

//取消掉當前所有的下載圖片的operation
- (void)cancelAll;

/**
 * Check one or more operations running
 */

//check一下是否有一個或者多個operation正在執行(簡單來說就是check是否有圖片在下載)
- (BOOL)isRunning;

/**
 *  Async check if image has already been cached
 *
 *  @param url              image url
 *  @param completionBlock  the block to be executed when the check is finished
 *  
 *  @note the completion block is always executed on the main queue
 */

//根據url判斷某張圖片是否緩存(block中攜帶一個bool值的參數用于判斷)
//之前的方法是 - (BOOL)cachedImageExistsForURL:(NSURL *)url;
- (void)cachedImageExistsForURL:(nullable NSURL *)url
                 completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;

/**
 *  Async check if image has already been cached on disk only
 *
 *  @param url              image url
 *  @param completionBlock  the block to be executed when the check is finished
 *
 *  @note the completion block is always executed on the main queue
 */

//url對應的圖片是否緩存到磁盤(跟上面那個方法類似)
- (void)diskImageExistsForURL:(nullable NSURL *)url
               completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;


/**
 *Return the cache key for a given URL
 */

//通過image的url返回image存在緩存里的key(為什么不直接使用url當key?)
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url;

 

然后我們進入SDWebImageManager.m看看

#import "SDWebImageManager.h"
#import <objc/message.h>
#import "NSImage+WebCache.h" //4.0新增(反正3.8版本沒有,同時增加了UIView+WebCache.h)

@interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>//內部類

@property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
@property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock;
@property (strong, nonatomic, nullable) NSOperation *cacheOperation;

@end

@interface SDWebImageManager ()

@property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache;
@property (strong, nonatomic, readwrite, nonnull) SDWebImageDownloader *imageDownloader;
@property (strong, nonatomic, nonnull) NSMutableSet<NSURL *> *failedURLs;
@property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageCombinedOperation *> *runningOperations;

@end

@implementation SDWebImageManager
//單例
+ (nonnull instancetype)sharedManager {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
    instance = [self new];
});
return instance;
}
//如下
- (nonnull instancetype)init {
   SDImageCache *cache = [SDImageCache sharedImageCache];
   SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
   return [self initWithCache:cache downloader:downloader];
}
/* 初始化方法.
 * 1.獲得一個SDImageCache的單例.
 * 2.獲取一個SDWebImageDownloader的單例.
 * 3.新建一個MutableSet來存儲下載失敗的url.
 * 4.新建一個用來存儲下載operation的可變數組.
 * 為什么不用MutableArray儲存下載失敗的URL?
 * 因為NSSet類有一個特性,就是Hash.實際上NSSet是一個哈希表,哈希表比數組優秀的地方是什么呢?就是查找速度快.
 * 查找同樣一個元素,哈希表只需要通過key即可取到,而數組至少需要遍歷依次.因為SDWebImage里有關失敗URL的業務需求是,一個失敗的URL只需要儲存一次.這樣的話Set自然比Array更合適.
 */
- (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader {
if ((self = [super init])) {
    _imageCache = cache;
    _imageDownloader = downloader;
    _failedURLs = [NSMutableSet new];
    _runningOperations = [NSMutableArray new];
}
return self;
}

/*
 * 利用Image的URL生成一個緩存時需要的key.
 * 這里有兩種情況,第一種是如果檢測到cacheKeyFilter不為空時,利用cacheKeyFilter來處理URL生成一個key.
 * 如果為空,那么直接返回URL的string內容,當做key
 */
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
   if (!url) {
    return @"";
   }

   if (self.cacheKeyFilter) {
      return self.cacheKeyFilter(url);
   } else {
      return url.absoluteString;
   }
}
/*
 * 檢測一張圖片是否已被緩存.
 * 首先檢測內存緩存是否存在這張圖片,如果有,completionBlock(YES).
 * 如果內存緩存里沒有這張圖片,那么調用diskImageExistsWithKey這個方法去硬盤緩存里找
 * 這里要說明下,之前的版本是直接返回一個bool值,改版后返回一個block,block中有一個bool的參數
 */
- (void)cachedImageExistsForURL:(nullable NSURL *)url
                 completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
   NSString *key = [self cacheKeyForURL:url];

   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);
       }
    }];
 }
//同上
- (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);
      }
  }];
}

//通過url建立一個operation用來下載圖片(主要的方法,會做詳解)
- (id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
                                 options:(SDWebImageOptions)options
                                progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                               completed:(nullable SDInternalCompletionBlock)completedBlock {
// Invoking this method without a completedBlock is pointless
   NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead");

// Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't
// throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
   //解決拋出異常警告
   if ([url isKindOfClass:NSString.class]) {
      url = [NSURL URLWithString:(NSString *)url];
   }

// Prevents app crashing on argument type error like sending NSNull instead of NSURL
   //預防崩潰
   if (![url isKindOfClass:NSURL.class]) {
    url = nil;
   }

   __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
   __weak SDWebImageCombinedOperation *weakOperation = operation;

   BOOL isFailedUrl = NO;
   if (url) {
     /*
      * 創建一個互斥鎖防止現在有別的線程修改failedURLs.
      * 判斷這個url是否是fail過的.如果url failed過的那么isFailedUrl就是true    
      */
    @synchronized (self.failedURLs) {
        isFailedUrl = [self.failedURLs containsObject:url];
    }
  }
   /*
    * 如果url不存在那么直接返回一個block,如果url存在.那么繼續進行判斷
    * options與SDWebImageRetryFailed這個option進行按位與操作.判斷用戶的options里是否有retry這個option
    * 如果用戶的options里沒有retry這個選項并且isFaileUrl 是true.那么就回調一個error的block,并返回operation
    */
   if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
      [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url];
      return operation;
  }
   //創建一個互斥鎖防止現在有別的線程修改runningOperations
   @synchronized (self.runningOperations) {
    [self.runningOperations addObject:operation];
   }
   NSString *key = [self cacheKeyForURL:url];
   //cacheOperation是一個用來下載圖片并且緩存的operation
   operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
       //判斷operation這時候有沒有執行cancel操作,如果cancel掉了就把這個operation從我們的operation數組里remove掉然后return
       if (operation.isCancelled) {
          [self safelyRemoveOperationFromRunning:operation];
          return;
      }

       if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
        if (cachedImage && options & SDWebImageRefreshCached) {
            // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image
            // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
            [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
        /*
         * 下面都是判斷我們的options里包含哪些SDWebImageOptions,然后給我們的downloaderOptions相應的添加對應的SDWebImageDownloaderOptions. 
         * downloaderOptions |= SDWebImageDownloaderLowPriority這種表達式的意思等同于
         * downloaderOptions = downloaderOptions | SDWebImageDownloaderLowPriority
         */
        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;

        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;
        }
        //調用imageDownloader去下載image并且返回執行這個request的download的operation
        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) {
                // Do nothing if the operation was cancelled
                // See #699 for more details
                // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data
            } else if (error) {
                [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) {
                    @synchronized (self.failedURLs) {
                        [self.failedURLs addObject:url];
                    }
                }
            }
            else {
                if ((options & SDWebImageRetryFailed)) {
                    @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
                } 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), ^{
                        //轉換圖片
                        UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];

                        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];
            }
        }];
        __weak typeof(subOperationToken)weakSubOperationToken = subOperationToken;
        operation.cancelBlock = ^{
            [self.imageDownloader cancel:weakSubOperationToken];
            __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;
}

//根據url緩存圖片(說明了使用sdwebimageManager是自帶緩存的)
- (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url {
        if (image && url) {
        NSString *key = [self cacheKeyForURL:url];
        [self.imageCache storeImage:image forKey:key toDisk:YES completion:nil];
    }
}
//取消所有任務
- (void)cancelAll {
    @synchronized (self.runningOperations) {
    NSArray<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy];
    [copiedOperations makeObjectsPerformSelector:@selector(cancel)];
    [self.runningOperations removeObjectsInArray:copiedOperations];
  }
}
//判斷當前任務是否執行
- (BOOL)isRunning {
   BOOL isRunning = NO;
   @synchronized (self.runningOperations) {
    isRunning = (self.runningOperations.count > 0);
  }
  return isRunning;
}
//安全移除某個任務
- (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
    @synchronized (self.runningOperations) {
    if (operation) {
        [self.runningOperations removeObject:operation];
      }
   } 
}

- (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
                         completion:(nullable SDInternalCompletionBlock)completionBlock
                              error:(nullable NSError *)error
                                url:(nullable NSURL *)url {
  [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES url:url];
}

- (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
                         completion:(nullable SDInternalCompletionBlock)completionBlock
                              image:(nullable UIImage *)image
                               data:(nullable NSData *)data
                              error:(nullable NSError *)error
                          cacheType:(SDImageCacheType)cacheType
                           finished:(BOOL)finished
                                url:(nullable NSURL *)url {
    dispatch_main_async_safe(^{
    if (operation && !operation.isCancelled && completionBlock) {
        completionBlock(image, data, error, cacheType, finished, url);
    }
  });
}

@end


@implementation SDWebImageCombinedOperation

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

- (void)cancel {
self.cancelled = YES;
if (self.cacheOperation) {
    [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;
  }
}

 

 

來自:http://www.jianshu.com/p/2439cb31993d

 

 本文由用戶 Mar86T 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!