SDWebImage源碼解析

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.lxweimin.com/p/277b688b0384
    最后,SDWebImage博大精深,日后還需潛心鉆研,這篇博客只是為了記錄自己學習的一個過程,日后復習方便,如有不對,望提供寶貴意見,謝謝~
    另附上參考文章鏈接:
    http://www.lxweimin.com/p/277b688b0384
    http://blog.csdn.net/cordova/article/details/54708029
    http://www.lxweimin.com/p/93696717b4a3
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容