前言
SDWebImageManager
是 SDWebImage
中最核心的類了,但是源代碼卻是非常簡單的。之所以能做到這一點,都歸功于功能的良好分類。
有了SDWebImageManager
這個基石,我們就能做很多其他的有意思的事情。比如給各種view綁定一個URL,就能顯示圖片的功能,有了Options,就能滿足多種應用場景的圖片下載任務。
讀源碼既能讓我們更好地使用該框架,又能讓我們學到很多知識,還能讓我們懂得如何去擴充現(xiàn)有的功能。
SDWebImageOptions
SDWebImageOptions
作為下載的選項提供了非常多的子項,用法和注意事項我都寫在代碼的注釋中了:
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.
*/
/// 每一個下載都會提供一個URL,如果這個URL是錯誤,SD就會把它放入到黑名單之中,
/// 黑名單中的URL是不會再次進行下載的,但是,當設置了該選項時,SD會將其在黑名單中移除,重新下載該URL,
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.
*/
/// 一般來說,下載都是按照一定的先后順序開始的,但是該選項能夠延遲下載,也就說他的權(quán)限比較低,權(quán)限比他高的在他前邊下載
SDWebImageLowPriority = 1 << 1,
/**
* This flag disables on-disk caching
*/
/// 該選項要求SD只把圖片緩存到內(nèi)存中,不緩存到disk中
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.
* 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.
*/
/// 有這么一種使用場景,如果一個圖片的資源發(fā)生了改變。但是url并沒有變,我們就可以使用該選項來刷新數(shù)據(jù)了
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.
*/
/// 支持切換到后臺也能下載
SDWebImageContinueInBackground = 1 << 5,
/**
* Handles cookies stored in NSHTTPCookieStore by setting
* NSMutableURLRequest.HTTPShouldHandleCookies = YES;
*/
/// 使用Cookies
SDWebImageHandleCookies = 1 << 6,
/**
* Enable to allow untrusted SSL certificates.
* 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.
*/
/// 高權(quán)限
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.
*/
/// 一般情況下,placeholder image 都會在圖片下載完成前顯示,該選項將設置placeholder image在下載完成之后才能顯示
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 delegate
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
*/
/// 該選項允許我們在圖片下載完成后不會立刻給view設置圖片,比較常用的使用場景是給賦值的圖片添加動畫
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.
*/
/// 壓縮大圖片
SDWebImageScaleDownLargeImages = 1 << 12
};
Block
typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL);
typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL);
typedef NSString * _Nullable (^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable url);
我們在平時的開發(fā)中,使用Block可以參考上邊的使用方法,XXXxxxCompletionBlock這種命名應該是Apple的風格。
SDWebImageManagerDelegate
使用協(xié)議增加了我們編程的靈活性,SDWebImageManagerDelegate
提供了兩個方法
- 在緩存中沒發(fā)現(xiàn)圖片,控制是不是下載該圖片
- 自由轉(zhuǎn)換圖片
代碼:
@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.
*/
- (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
SDWebImageCombinedOperation
SDWebImageCombinedOperation
是對每一個下載任務的封裝,重要的是它提供了一個取消功能。
@interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
@property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
@property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock;
@property (strong, nonatomic, nullable) NSOperation *cacheOperation;
@end
SDWebImageManager
1.屬性
@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
2.初始化(非常典型的初始化)
+ (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];
}
- (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;
}
3.URL => key
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
if (!url) {
return @"";
}
if (self.cacheKeyFilter) {
return self.cacheKeyFilter(url);
} else {
return url.absoluteString;
}
}
4.查看圖片是否已經(jīng)緩存
現(xiàn)在內(nèi)容中讀取,沒有的話再去disk讀取。
- (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);
}
}];
}
5.查看是否已經(jīng)緩存到了硬盤
- (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);
}
}];
}
6.核心下載方法
對于一個比較復雜的函數(shù),我們往往只需要左下邊三件事就可以了:
- 處理參數(shù)相關(guān)的異常
- 處理復雜的邏輯
- 返回數(shù)據(jù)
這三條適合所有的函數(shù),由于這個方法的邏輯比較復雜,我把詳細的注釋都寫到代碼中了
- (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
/// 1.如果想預先下載圖片,使用[SDWebImagePrefetcher prefetchURLs]取代本方法
/// 預下載圖片是有很多種使用場景的,當我們使用SDWebImagePrefetcher下載圖片后,之后使用該圖片時就不用再網(wǎng)絡上下載了。
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.
/// 2.XCode有時候經(jīng)常會犯一些錯誤,當用戶給url賦值了字符串的時候,XCode也沒有報錯,因此這里提供一種
/// 錯誤修正的處理。
if ([url isKindOfClass:NSString.class]) {
url = [NSURL URLWithString:(NSString *)url];
}
// Prevents app crashing on argument type error like sending NSNull instead of NSURL
/// 3.防止參數(shù)的其他錯誤
if (![url isKindOfClass:NSURL.class]) {
url = nil;
}
/// 4.operation會被作為該方法的返回值,但operation的類型是SDWebImageCombinedOperation,是一個封裝的對象,并不是一個NSOperation
__block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
__weak SDWebImageCombinedOperation *weakOperation = operation;
/// 5.在圖片的下載中,會有一些下載失敗的情況,這時候我們把這些下載失敗的url放到一個集合中去,
/// 也就是加入了黑名單中,默認是不會再繼續(xù)下載黑名單中的url了,但是也有例外,當options被設置為
/// SDWebImageRetryFailed的時候,會嘗試進行重新下載。
BOOL isFailedUrl = NO;
if (url) {
@synchronized (self.failedURLs) {
isFailedUrl = [self.failedURLs containsObject:url];
}
}
/// 6.會有兩種情況讓我們停止下載這個url指定的圖片:
/// - url的長度為0
/// - options并沒有選擇SDWebImageRetryFailed(重新下載錯誤url)且這個url在黑名單之中
/// 調(diào)用完成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;
}
/// 7.排除了所有的錯誤可能后,我們就先把這個operation添加到正在運行操作的數(shù)組中
/// 這里沒有判斷self.runningOperations是不是包含了operation,
/// 說明肯定會在下邊的代碼中做判斷,如果存在就刪除operation
@synchronized (self.runningOperations) {
[self.runningOperations addObject:operation];
}
NSString *key = [self cacheKeyForURL:url];
/// 8.self.imageCache的queryCacheOperationForKey方法是異步的獲取指定key的圖片,
/// 但是這個方法的operation是同步返回的,也就是說下邊的代碼會直接執(zhí)行到return那里。
operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
/// (8.1).這個Block會在查詢完指定的key的圖片后調(diào)用,由` dispatch_async(self.ioQueue, ^{`
/// 這個可以看出,實在異步線程采用串行的方式在調(diào)用,任務在self.imageCache的ioQueue中一個一個執(zhí)行,是線程安全的
/// (8.2).如果每次調(diào)用loadImage方法都會生成一個operation,如果我們想取消某個下載任務
/// 再設計上來說,只要把響應的operation.isCancelled設置為NO,那么下載就會被取消。
if (operation.isCancelled) {
[self safelyRemoveOperationFromRunning:operation];
return;
}
/// (8.3).代碼來到這里,我們就要根據(jù)是否有緩存的圖片來做出響應的處理
/// 如果沒有獲取到緩存圖片或者需要刷新緩存圖片我們應該通過網(wǎng)絡獲取圖片,但是這里增加了一個額外的控制
/// 根據(jù)delegate的imageManager:shouldDownloadImageForURL:獲取是否下載的權(quán)限,返回YES,就繼續(xù)下載
if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
/// (8.3.1).這里需要注意了,當圖片已經(jīng)下載了,Options又選擇了SDWebImageRefreshCached
/// 就會觸發(fā)一次completionBlock回調(diào),這說明這個下載的回調(diào)不是只觸發(fā)一次的
/// 如果使用了dispatch_group_enter和dispatch_group_leave就一定要注意了
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
/// (8.3.2).這里是SDWebImageOptions到SDWebImageDownloaderOptions的轉(zhuǎn)換
/// 其實就是0 |= xxx
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;
/// (8.3.3).已經(jīng)緩存且SDWebImageRefreshCached的比較特殊
if (cachedImage && options & SDWebImageRefreshCached) {
// force progressive off if image already cached but forced refreshing
/// (8.3.3.1).SDWebImageDownloaderProgressiveDownload為 1<<1 ,
/*
由于當options == SDWebImageRefreshCached時,downloaderOptions |= SDWebImageDownloaderUseNSURLCache(1 << 2)
00000000 | 00000100 => 00000100
~SDWebImageDownloaderProgressiveDownload : ~ 00000010 => 111111101
00000100 & 11111101 => 00000100
*/
downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
// ignore image read from NSURLCache if image if cached but force refreshing
/// (8.3.3.2). 00000100 | 00001000 => 00001100
/// 通過這種位的運算,就能夠給同一個值賦值兩種轉(zhuǎn)態(tài)
downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
}
/// (8.3.4).下載圖片
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) {
/// (8.3.4.1).發(fā)生錯誤就返回
[self callCompletionBlockForOperation:strongOperation completion:completedBlock error:error url:url];
/// (8.3.4.2).除了下邊這幾種情況之外的情況則把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 {
/// (8.3.4.3).如果是SDWebImageRetryFailed就在黑名單中移除,不管有沒有
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];
}
}
/// (8.3.4.4).完成了就把該任務在正運行著的數(shù)組中刪除
if (finished) {
[self safelyRemoveOperationFromRunning:strongOperation];
}
}];
/// (8.3.5).設置取消的回調(diào)
operation.cancelBlock = ^{
[self.imageDownloader cancel:subOperationToken];
__strong __typeof(weakOperation) strongOperation = weakOperation;
[self safelyRemoveOperationFromRunning:strongOperation];
};
} else if (cachedImage) {
__strong __typeof(weakOperation) strongOperation = weakOperation;
[self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
[self safelyRemoveOperationFromRunning:operation];
} else {
// Image not in cache and download disallowed by delegate
/// (8.4).既沒有緩存也下載了代理不允許的圖片
__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;
}
7.保存圖片到緩存區(qū)
- (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];
}
}
8.取消所有的下載
- (void)cancelAll {
@synchronized (self.runningOperations) {
NSArray<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy];
[copiedOperations makeObjectsPerformSelector:@selector(cancel)];
[self.runningOperations removeObjectsInArray:copiedOperations];
}
}
9.查看是否下載完畢
- (BOOL)isRunning {
BOOL isRunning = NO;
@synchronized (self.runningOperations) {
isRunning = (self.runningOperations.count > 0);
}
return isRunning;
}
10.安全移除任務
要想安全的操作數(shù)組,只要給數(shù)組本身加個鎖就行了,但@synchronized的性能不是很好
- (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
@synchronized (self.runningOperations) {
if (operation) {
[self.runningOperations removeObject:operation];
}
}
}
11.回調(diào)
- (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);
}
});
}
12.SDWebImageCombinedOperation實現(xiàn)方法
- (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;
}
}
總結(jié)
SD的源碼讀了大部分了,也收獲很大,現(xiàn)在寫代碼的風格也越來越靠近這種框架風格,我們應該為寫出的每一個函數(shù)負責。
在上一篇SDWebImage源碼解讀之SDWebImageDownloader的評論區(qū),有小伙伴提出了SD在特定使用場景會崩潰的情況,我也做了一些實驗。
- (void)test {
NSURL *url = [NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/1432482-dcc38746f56a89ab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[manager loadImageWithURL:url options:SDWebImageRefreshCached progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
dispatch_group_leave(group);
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"下載完成了");
});
}
在上邊的函數(shù)中,我使用了dispatch_group_t
dispatch_group_enter
dispatch_group_leave
目的是等待所有的異步任務完成。
enter和leave方法必須成對出現(xiàn),如果調(diào)用leave的次數(shù)多于enter就會崩潰,當我們使用SD時,如果Options設置為SDWebImageRefreshCached,那么這個completionBlock至少會調(diào)用兩次,首先返回緩存中的圖片。其次在下載完成后再次調(diào)用Block,這也就是崩潰的原因。
要想重現(xiàn)上邊方法的崩潰,等圖片下載完之后,再從新調(diào)用該方法就行。
SD默認下載的圖片會緩存進內(nèi)存和disk中。