美文网首页
SDWebImage源码解析

SDWebImage源码解析

作者: 329fd8af610c | 来源:发表于2017-11-02 23:24 被阅读13次

    SDWebImage 是一个众所周知加载图片的框架,对常用UI元素:UIImageView,UIButton和MKAnnotationView提供了Category类别扩展,实现一个异步查询,下载并且支持缓存的功能,整个框架各个类分工明确,接口调用灵活,代码风格很值得学习。

    1. 调用方式非常简单,UI分类类似接口如下:
    - (void)sd_setImageWithURL:(NSURL *)url;
    - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
    - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
    - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
    - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
    - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
    - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
    

    上述几种方法最终都会调用最后一个参数最齐全的方法:在block中拿到image等数据之后处理自己的逻辑。

    1. 思路流程图
      纵观整个框架,其实核心类就三个 SDWebImageManger,SDWebImageDownloader,SDWebImageCache ,分类UIImageView+WebCache和UIButton+WebCache为下载图片提供接口,SDWebImageManger负责协调SDWebImageCache完成缓存查询,存储,清除和SDWebImageDownloader图片下载,缓存。


      图一 简单流程图.png

      为了方便自己及他人更好的理解跟吸收,附上官方文档说明图:


      图二 官方文档图.png
      图三 官方文档图.png
    2. 源码解析
      在引入正题之前先来了解几个枚举
    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.
         * 默认情况下,当一个 URL 下载失败,该URL被列入黑名单,将不会继续尝试下载
    
         * This flag disable this blacklisting.
         * 此标志取消黑名单
    
         */
        SDWebImageRetryFailed = 1 << 0,
    
        /**
         * By default, image downloads are started during UI interactions, this flags disable this feature,
         * 默认情况下,在 UI 交互时也会启动图像下载,此标记取消这一功能
    
         * leading to delayed download on UIScrollView deceleration for instance.
         * 会延迟下载,UIScrollView停止滚动之后再继续下载
         * 下载事件监听的运行循环模式是 NSDefaultRunLoopMode
         */
        SDWebImageLowPriority = 1 << 1,
    
        /**
         * This flag disables on-disk caching
         * 禁用磁盘缓存
         */
        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.
         * 默认情况下,图像只会在下载完后显示
    
         */
        SDWebImageProgressiveDownload = 1 << 3,
    
        /**
         * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
         * 即使图像被缓存,遵守 HTPP 响应的缓存控制,如果需要,从远程刷新图像
    
         * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
         * 磁盘缓存将由 NSURLCache 处理,而不是 SDWebImage,这会对性能有轻微的影响
    
         * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.
         * 此选项有助于处理同一个请求 URL 的图像发生变化
    
         * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.
         * 如果缓存的图像被刷新,会调用一次 completion block,并传递最终的图像
    
         *
         * Use this flag only if you can't make your URLs static with embedded cache busting parameter.
         * 仅在无法使用嵌入式缓存清理参数确定图像 URL 时,使用此标记
    
         */
        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
         * 在 iOS 4+,当 App 进入后台后仍然会继续下载图像。这是向系统请求额外的后台时间以保证下载请求完成的
    
         * extra time in background to let the request finish. If the background task expires the operation will be cancelled.
         * 如果后台任务过期,请求将会被取消
    
         */
        SDWebImageContinueInBackground = 1 << 5,
    
        /**
         * Handles cookies stored in NSHTTPCookieStore by setting
         * 通过设置
    
         * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
         * 处理保存在 NSHTTPCookieStore 中的 cookies
    
         */
        SDWebImageHandleCookies = 1 << 6,
    
        /**
         * Enable to allow untrusted SSL certificates.
         * 允许不信任的 SSL 证书
    
         * Useful for testing purposes. Use with caution in production.
         * 可以出于测试目的使用,在正式产品中慎用
    
         */
        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.
         */
        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.
         */
        SDWebImageDelayPlaceholder = 1 << 9,
    
        /**
         * We usually don't call transformDownloadedImage delegate method on animated images,
         * 通常不会在可动画的图像上调用 transformDownloadedImage 代理方法,因为大多数转换代码会破坏动画文件
    
         * as most transformation code would mangle it.
         * Use this flag to transform them anyway.
         * 使用此标记尝试转换
         */
        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
         */
        SDWebImageAvoidAutoSetImage = 1 << 11
    };
    
    typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
        //同SDWebImageLowPriority 意义相同
        SDWebImageDownloaderLowPriority = 1 << 0,
        //同SDWebImageProgressiveDownload 意义相同
        SDWebImageDownloaderProgressiveDownload = 1 << 1,
    
        /**
         * By default, request prevent the use of NSURLCache. With this flag, NSURLCache
         * is used with default policies.
         默认情况下,请求阻止NSURLCache的使用,使用此标记,NSURLCache使用时是默认政策
         */
        SDWebImageDownloaderUseNSURLCache = 1 << 2,
    
        /**
         * Call completion block with nil image/imageData if the image was read from NSURLCache
         * (to be combined with `SDWebImageDownloaderUseNSURLCache`).
         从NSURLCache中获取的image,回调completion时参数imge/imageData传nil
         */
    
        SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
        /**
         * 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.
         同SDWebImageContinueInBackground 意义相同
         */
    
        SDWebImageDownloaderContinueInBackground = 1 << 4,
    
        /**
         * Handles cookies stored in NSHTTPCookieStore by setting 
         * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
         设置NSMutableURLRequest.HTTPShouldHandleCookies = YES,允许在NSHTTPCookieStore中操作cookies
         */
        SDWebImageDownloaderHandleCookies = 1 << 5,
    
        /**
         * Enable to allow untrusted SSL certificates.
         测试环境允许使用过不信任SSL证书,生产环境要小心
         * Useful for testing purposes. Use with caution in production.
         */
        SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6,
    
        /**
         * Put the image in the high priority queue.
           图片下载操作至于高优先级队列
         */
        SDWebImageDownloaderHighPriority = 1 << 7,
    };
    
    typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
        /**
         * Default value. All download operations will execute in queue style (first-in-first-out).
         操作默认执行方式,所有下载操作按照队列方式执行
         */
        SDWebImageDownloaderFIFOExecutionOrder,
    
        /**
         * All download operations will execute in stack style (last-in-first-out).
         所有下载操作按照栈的方式执行
         */
        SDWebImageDownloaderLIFOExecutionOrder
    };
    

    下面是下载过程的代码
    1..SDWebImageManager 执行下载操作

    - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
                                             options:(SDWebImageOptions)options
                                            progress:(SDWebImageDownloaderProgressBlock)progressBlock
                                           completed:(SDWebImageCompletionWithFinishedBlock)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;
    
        //1.判断传入的url是否是请求失败的url
        BOOL isFailedUrl = NO;
        @synchronized (self.failedURLs) {
            isFailedUrl = [self.failedURLs containsObject:url];
        }
    
        //针对url(如果没有/请求失败的url没有设置SDWebImageRetryFailed选项)
        if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
            dispatch_main_sync_safe(^{
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
                completedBlock(nil, error, SDImageCacheTypeNone, YES, url);
            });
            return operation;
        }
    
        // 将当前此次下载图片的operation添加到操作缓存中
        @synchronized (self.runningOperations) {
            [self.runningOperations addObject:operation];
        }
        //通过url找到对应cachekey
        NSString *key = [self cacheKeyForURL:url];
        //2.imageCache根据cachekey去查找内存中是否存储image
        operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {
            // 查到之后如果operation取消,就从操作缓存中移除
            if (operation.isCancelled) {
                @synchronized (self.runningOperations) {
                    [self.runningOperations removeObject:operation];
                }
    
                return;
            }
    
            //2.1 imageCache 对查找结果处理 (没有图片||SDWebImageRefreshCached设置属性)&&(代理没有实现方法||代理实现方法返回BOOL)
            if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
                //2.1.1 存在image && SDWebImageRefreshCached 直接调用block进行回调
                if (image && options & SDWebImageRefreshCached) {
                    dispatch_main_sync_safe(^{
                        // 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.
                        completedBlock(image, nil, cacheType, YES, url);
                    });
                }
    
                // download if no image or requested to refresh anyway, and download allowed by delegate
                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 (image && 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;
                }
                //2.1.2 image不存在 imageDownloader开始下载图片
                id <SDWebImageOperation> subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) {
                    __strong __typeof(weakOperation) strongOperation = weakOperation;
                    //在下载回调中处理
                    //1..操作取消,不做处理
                    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
                    }
                    //2..下载错误,回调block
                    else if (error) {
                        dispatch_main_sync_safe(^{
                            if (strongOperation && !strongOperation.isCancelled) {
                                completedBlock(nil, error, SDImageCacheTypeNone, finished, 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];
                            }
                        }
                    }
                    //3.. 下载成功
                    else {
                        //3..1..SDWebImageRetryFailed 设置之后将请求失败的url从failedURLs数组中移除,默认情况是url一旦请求不成功,默认加入failedURLs,不在发送请求
                        if ((options & SDWebImageRetryFailed)) {
                            @synchronized (self.failedURLs) {
                                [self.failedURLs removeObject:url];
                            }
                        }
                        //3..2..下载之后进行缓存
                        BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
    
                        //缓存图片分为以下三种情况
                        //3..2..1.. (SDWebImageRefreshCached && 缓存image存在 && downloadimage不存在) 不做任何处理
                        if (options & SDWebImageRefreshCached && image && !downloadedImage) {
                            // Image refresh hit the NSURLCache cache, do not call the completion block
                        }
                        //3..2..2..(downloadimage存在 && 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), ^{
                                //downloadimage经代理操作的transformedImage
                                UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
    
                                if (transformedImage && finished) {
                                    BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
                                    // imageCache 进行缓存图片(图片,是否重新计算大小,大小,cachekey,是否只存在disk中)
                                    [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:(imageWasTransformed ? nil : data) forKey:key toDisk:cacheOnDisk];
                                }
                                //上述异步操作完成之后回调block
                                dispatch_main_sync_safe(^{
                                    if (strongOperation && !strongOperation.isCancelled) {
                                        completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url);
                                    }
                                });
                            });
                        }
                        //3..2..3..直接将downloadimage进行存储
                        else {
                            if (downloadedImage && finished) {
                                [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk];
                            }
    
                            dispatch_main_sync_safe(^{
                                if (strongOperation && !strongOperation.isCancelled) {
                                    completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url);
                                }
                            });
                        }
                    }
                    //4.. 下载成功之后并且完成以后,将此次下载的operation从下载缓存中移除
                    if (finished) {
                        @synchronized (self.runningOperations) {
                            if (strongOperation) {
                                [self.runningOperations removeObject:strongOperation];
                            }
                        }
                    }
                }];
                //2.1.3  操作取消
                operation.cancelBlock = ^{
                    [subOperation cancel];
                    
                    @synchronized (self.runningOperations) {
                        __strong __typeof(weakOperation) strongOperation = weakOperation;
                        if (strongOperation) {
                            [self.runningOperations removeObject:strongOperation];
                        }
                    }
                };
            }
            //2.2 缓存image存在
            else if (image) {
                dispatch_main_sync_safe(^{
                    __strong __typeof(weakOperation) strongOperation = weakOperation;
                    if (strongOperation && !strongOperation.isCancelled) {
                        completedBlock(image, nil, cacheType, YES, url);
                    }
                });
                @synchronized (self.runningOperations) {
                    [self.runningOperations removeObject:operation];
                }
            }
            //2.3 其他情况,缓存image不存在,同时delegate不允许下载
            else {
                // Image not in cache and download disallowed by delegate
                dispatch_main_sync_safe(^{
                    __strong __typeof(weakOperation) strongOperation = weakOperation;
                    if (strongOperation && !weakOperation.isCancelled) {
                        completedBlock(nil, nil, SDImageCacheTypeNone, YES, url);
                    }
                });
                @synchronized (self.runningOperations) {
                    [self.runningOperations removeObject:operation];
                }
            }
        }];
    
        return operation;
    }
    

    2.. SDImageCache执行查找操作,其中有几个关键的属性

    @property (strong, nonatomic) NSCache *memCache;// 系统缓存类,根据cachekey查找对象
    @property (strong, nonatomic) NSString *diskCachePath;// 用于存储磁盘文件path
    @property (strong, nonatomic) NSMutableArray *customPaths;// 自定义path
    @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue;
    //计算image花费的内存
    FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
        return image.size.height * image.size.width * image.scale * image.scale;
    }
    // 保质期是一周
    static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7;
    
    //cache 根据cachekey查找image
    - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
       此处...非空判断
        //1. 从内存中查找 NSCache中根据key查找object
        // First check the in-memory cache...
        UIImage *image = [self imageFromMemoryCacheForKey:key];
        if (image) {
            doneBlock(image, SDImageCacheTypeMemory);
            return nil;
        }
    
        //2.从磁盘查找,主要是根据key找到文件路径,取出其文件路径下的image
        NSOperation *operation = [NSOperation new];
        dispatch_async(self.ioQueue, ^{
            if (operation.isCancelled) {
                return;
            }
    
            @autoreleasepool {
                UIImage *diskImage = [self diskImageForKey:key];
                //diskimage && 从磁盘中发现image之后要存储到内存中
                if (diskImage && self.shouldCacheImagesInMemory) {
                    //存储image需要花费的内存(图片的width*height*scale*scale)
                    NSUInteger cost = SDCacheCostForImage(diskImage);
                    //存进内存
                    [self.memCache setObject:diskImage forKey:key cost:cost];
                }
                //成功存储之后进行回调
                dispatch_async(dispatch_get_main_queue(), ^{
                    doneBlock(diskImage, SDImageCacheTypeDisk);
                });
            }
        });
        return operation;
    }
    //其中涉及得到的方法,请自行查看,此处省略
    

    3.. SDWebImageDownloader执行下载操作

    //下载图片
    - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock {
        __block SDWebImageDownloaderOperation *operation;
        __weak __typeof(self)wself = self;
    
        [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^{
            // 如果是第一次创建,实际回调的是createblock
            //限制request的时间限制
            NSTimeInterval timeoutInterval = wself.downloadTimeout;
            if (timeoutInterval == 0.0) {
                timeoutInterval = 15.0;
            }
    
            // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
            //构建请求的request 设置request的属性
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
            request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
            request.HTTPShouldUsePipelining = YES;
            //request的allHTTPHeaderFields 根据headersFilter 中的block中的url跟dic 推出dic
            if (wself.headersFilter) {
                request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]);
            }
            else {
                request.allHTTPHeaderFields = wself.HTTPHeaders;
            }
            //针对 request构建operation
            operation = [[wself.operationClass alloc] initWithRequest:request
                                                            inSession:self.session
                                                              options:options
                                                             progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                                                 SDWebImageDownloader *sself = wself;
                                                                 if (!sself) return;
                                                                 __block NSArray *callbacksForURL;
                                                                 dispatch_sync(sself.barrierQueue, ^{
                                                                     //url对应的value
                                                                     callbacksForURL = [sself.URLCallbacks[url] copy];
                                                                 });
                                                                 for (NSDictionary *callbacks in callbacksForURL) {
                                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                                         SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey];
                                                                         if (callback) callback(receivedSize, expectedSize);
                                                                     });
                                                                 }
                                                             }
                                                            completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                                                SDWebImageDownloader *sself = wself;
                                                                if (!sself) return;
                                                                __block NSArray *callbacksForURL;
                                                                dispatch_barrier_sync(sself.barrierQueue, ^{
                                                                    callbacksForURL = [sself.URLCallbacks[url] copy];
                                                                    if (finished) {
                                                                        [sself.URLCallbacks removeObjectForKey:url];
                                                                    }
                                                                });
                                                                for (NSDictionary *callbacks in callbacksForURL) {
                                                                    SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey];
                                                                    if (callback) callback(image, data, error, finished);
                                                                }
                                                            }
                                                            cancelled:^{
                                                                SDWebImageDownloader *sself = wself;
                                                                if (!sself) return;
                                                                dispatch_barrier_async(sself.barrierQueue, ^{
                                                                    [sself.URLCallbacks removeObjectForKey:url];
                                                                });
                                                            }];
            operation.shouldDecompressImages = wself.shouldDecompressImages;
            
            if (wself.urlCredential) {
                operation.credential = wself.urlCredential;
            } else if (wself.username && wself.password) {
                operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession];
            }
            
            if (options & SDWebImageDownloaderHighPriority) {
                operation.queuePriority = NSOperationQueuePriorityHigh;
            } else if (options & SDWebImageDownloaderLowPriority) {
                operation.queuePriority = NSOperationQueuePriorityLow;
            }
            // 下载到operation加入到下载队列中进行操作
            [wself.downloadQueue addOperation:operation];
            //设置operaton操作的操作顺序
            if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
                // Emulate LIFO execution order by systematically adding new operations as last operation's dependency
                [wself.lastAddedOperation addDependency:operation];
                wself.lastAddedOperation = operation;
            }
        }];
    
        return operation;
    }
    //其中涉及得到的方法,请自行查看,此处省略
    
    1. SDWebImage的特性
      为UIImageView,UIButton和MKAnnotationView进行了类别扩展,添加了web图片和缓存管理;
      是一个异步图片下载器;
      异步的内存+硬盘缓冲以及自动的缓冲过期处理;
      后台图片解压缩功能;
      可以保证相同的url(图片的检索key)不会被重复多次下载;
      可以保证假的无效url不会不断尝试去加载;
      保证主线程不会被阻塞;
      性能高;
      使用GCD和ARC;
    2. SDWebImage注意点⚠️:
      附上一个大神总结的:http://www.jianshu.com/p/277b688b0384
      最后,SDWebImage博大精深,日后还需潜心钻研,这篇博客只是为了记录自己学习的一个过程,日后复习方便,如有不对,望提供宝贵意见,谢谢~
      另附上参考文章链接:
      http://www.jianshu.com/p/277b688b0384
      http://blog.csdn.net/cordova/article/details/54708029
      http://www.jianshu.com/p/93696717b4a3

    相关文章

      网友评论

          本文标题:SDWebImage源码解析

          本文链接:https://www.haomeiwen.com/subject/dizapxtx.html