SDWebImage 解析之 SDWebImageManager

这里会做一些源码的解析,也会对使用较多的类或方法进行简单的介绍!
目前为止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. Facebook 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;
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容