簡(jiǎn)書博客已經(jīng)暫停更新殉农,想看更多技術(shù)博客請(qǐng)到:
相信對(duì)于廣大的iOS開發(fā)者蛛砰,對(duì)SDWebImage并不會(huì)陌生吨拗,這個(gè)框架通過給UIImageView和UIButton添加分類,實(shí)現(xiàn)一個(gè)異步下載圖片并且支持緩存的功能。整個(gè)框架的接口非常簡(jiǎn)潔,每個(gè)類的分工都很明確状知,是很值得大家學(xué)習(xí)的。
在使用這個(gè)框架的時(shí)候孽查,只需要提供一個(gè)下載的url和占位圖就可以在回調(diào)里拿到下載后的圖片:
[imageview sd_setImageWithURL:[NSURL URLWithString:@"pic.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
imageview.image = image;
NSLog(@"圖片加載完成");
}];
而且我們還可以不設(shè)置占位圖片饥悴,也可以不使用回調(diào)的block,非常靈活:
//圖片下載完成后直接顯示下載后的圖片
[imageview sd_setImageWithURL:[NSURL URLWithString:@"pic.jpg"]];
在最開始先簡(jiǎn)單介紹這個(gè)框架:
這個(gè)框架的核心類是SDWebImageManger
盲再,在外部有UIImageView+WebCache
和 UIButton+WebCache
為下載圖片的操作提供接口西设。內(nèi)部有SDWebImageManger
負(fù)責(zé)處理和協(xié)調(diào) SDWebImageDownloader
和 SDWebImageCache
:SDWebImageDownloader
負(fù)責(zé)具體的下載任務(wù),SDWebImageCache
負(fù)責(zé)關(guān)于緩存的工作:添加答朋,刪除贷揽,查詢緩存。
首先我們大致看一下這個(gè)框架的調(diào)用流程圖:
從這個(gè)流程圖里可以大致看出梦碗,該框架分為兩個(gè)層:UIKit層(負(fù)責(zé)接收下載參數(shù))和工具層(負(fù)責(zé)下載操作和緩存)禽绪。
OK~基本流程大概清楚了蓖救,我們看一下每個(gè)層具體實(shí)現(xiàn)吧~
UIKit層
該框架最外層的類是UIImageView +WebCache
,我們將圖片的URL印屁,占位圖片直接給這個(gè)類循捺。下面是這個(gè)類的公共接口:
// ============== UIImageView + WebCache.h ============== //
- (void)sd_setImageWithURL:(nullable NSURL *)url;
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder;
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options;
- (void)sd_setImageWithURL:(nullable NSURL *)url
completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
可以看出,這個(gè)類提供的接口非常靈活雄人,可以根據(jù)我們自己的需求來調(diào)用其中某一個(gè)方法从橘,而這些方法到最后都會(huì)走到:
// ============== UIView+ WebCache.m ============== //
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
而這個(gè)方法里面,調(diào)用的是UIView+WebCache
分類的:
// ============== UIView+ WebCache.m ============== //
- (void)sd_internalSetImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
operationKey:(nullable NSString *)operationKey
setImageBlock:(nullable SDSetImageBlock)setImageBlock
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
為什么不是UIImageView+WebCache而要上一層到UIView的分類里呢柠衍?
因?yàn)镾DWebImage框架也支持UIButton的下載圖片等方法洋满,所以需要在它們的父類:UIView里面統(tǒng)一一個(gè)下載方法。
簡(jiǎn)單看一下這個(gè)方法的實(shí)現(xiàn)(省略的代碼用...代替):
// ============== UIView+ WebCache.m ============== //
//valid key:UIImageView || UIButton
NSString *validOperationKey = operationKey ?: NSStringFromClass([self class]);
//UIView+WebCacheOperation 的 operationDictionary
//下面這行代碼是保證沒有當(dāng)前正在進(jìn)行的異步下載操作, 使它不會(huì)與即將進(jìn)行的操作發(fā)生沖突
[self sd_cancelImageLoadOperationWithKey:validOperationKey];
//添加臨時(shí)的占位圖(在不延遲添加占位圖的option下)
if (!(options & SDWebImageDelayPlaceholder)) {
dispatch_main_async_safe(^{
[self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock];
});
}
//如果url存在
if (url) {
...
__weak __typeof(self)wself = self;
//SDWebImageManager下載圖片
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager loadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
...
//dispatch_main_sync_safe : 保證block能在主線程進(jìn)行
dispatch_main_async_safe(^{
if (!sself) {
return;
}
if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) {
//image珍坊,而且不自動(dòng)替換 placeholder image
completedBlock(image, error, cacheType, url);
return;
} else if (image) {
//存在image牺勾,需要馬上替換 placeholder image
[sself sd_setImage:image imageData:data basedOnClassOrViaCustomSetImageBlock:setImageBlock];
[sself sd_setNeedsLayout];
} else {
//沒有image,在圖片下載完之后顯示 placeholder image
if ((options & SDWebImageDelayPlaceholder)) {
[sself sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock];
[sself sd_setNeedsLayout];
}
}
if (completedBlock && finished) {
completedBlock(image, error, cacheType, url);
}
});
}];
//在操作緩存字典(operationDictionary)里添加operation阵漏,表示當(dāng)前的操作正在進(jìn)行
[self sd_setImageLoadOperation:operation forKey:validOperationKey];
} else {
//如果url不存在驻民,就在completedBlock里傳入error(url為空)
dispatch_main_async_safe(^{
[self sd_removeActivityIndicator];
if (completedBlock) {
NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
completedBlock(nil, error, SDImageCacheTypeNone, url);
}
});
}
```
> 值得一提的是,在這一層履怯,使用一個(gè)字典``operationDictionary``專門用作存儲(chǔ)操作的緩存回还,隨時(shí)添加,刪除操作任務(wù)叹洲。
而這個(gè)字典是``UIView+WebCacheOperation``分類的關(guān)聯(lián)對(duì)象柠硕,它的存取方法使用運(yùn)行時(shí)來操作:
```objc
// ============== UIView+WebCacheOperation.m ============== //
//獲取關(guān)聯(lián)對(duì)象:operations(用來存放操作的字典)
- (SDOperationsDictionary *)operationDictionary {
SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
//存放操作的字典
if (operations) {
return operations;
}
//如果沒有,就新建一個(gè)
operations = [NSMutableDictionary dictionary];
objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return operations;
}
為什么不直接在
UIImageView+WebCache
里直接關(guān)聯(lián)這個(gè)對(duì)象呢运提?我覺得這里作者應(yīng)該是遵從面向?qū)ο蟮?strong>單一職責(zé)原則(SRP:Single responsibility principle)蝗柔,就連類都要履行這個(gè)職責(zé),何況分類呢民泵?這里作者專門創(chuàng)造一個(gè)分類UIView+WebCacheOperation
來管理操作緩存(字典)癣丧。
到這里,UIKit
層上面的東西都講完了栈妆,現(xiàn)在開始正式講解工具層胁编。
工具層
上文提到過,SDWebImageManager
同時(shí)管理SDImageCache
和SDWebImageDownloader
兩個(gè)類鳞尔,它是這一層的老大哥嬉橙。在下載任務(wù)開始的時(shí)候,SDWebImageManager
首先訪問SDImageCache
來查詢是否存在緩存寥假,如果有緩存憎夷,直接返回緩存的圖片。如果沒有緩存昧旨,就命令SDWebImageDownloader
來下載圖片拾给,下載成功后祥得,存入緩存,顯示圖片蒋得。以上是SDWebImageManager
大致的工作流程级及。
在詳細(xì)講解SDWebImageManager
是如何下載圖片之前,我們先看一下這個(gè)類的幾個(gè)重要的屬性:
// ============== SDWebImageManager.h ============== //
@property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache;//管理緩存
@property (strong, nonatomic, readwrite, nonnull) SDWebImageDownloader //下載器*imageDownloader;
@property (strong, nonatomic, nonnull) NSMutableSet<NSURL *> *failedURLs;//記錄失效url的名單
@property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageCombinedOperation *> *runningOperations;//記錄當(dāng)前正在執(zhí)行的操作
SDWebImageManager
下載圖片的方法只有一個(gè):
[SDWebImageManager.sharedManager loadImageWithURL:options:progress:completed:]
看一下這個(gè)方法的具體實(shí)現(xiàn):
// ============== SDWebImageManager.m ============== //
- (id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
options:(SDWebImageOptions)options
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDInternalCompletionBlock)completedBlock {
...
//在SDImageCache里查詢是否存在緩存的圖片
operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
...
//(沒有緩存圖片) || (即使有緩存圖片额衙,也需要更新緩存圖片) || (代理沒有響應(yīng)imageManager:shouldDownloadImageForURL:消息饮焦,默認(rèn)返回yes,需要下載圖片)|| (imageManager:shouldDownloadImageForURL:返回yes窍侧,需要下載圖片)
if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
//1. 存在緩存圖片 && 即使有緩存圖片也要下載更新圖片
if (cachedImage && options & SDWebImageRefreshCached) {
[self callCompletionBlockForOperation:weakOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
}
// 2. 如果不存在緩存圖片
...
//開啟下載器下載
//subOperationToken 用來標(biāo)記當(dāng)前的下載任務(wù)县踢,便于被取消
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) {
// 1. 如果任務(wù)被取消,則什么都不做伟件,避免和其他的completedBlock重復(fù)
} else if (error) {
//2. 如果有錯(cuò)誤
//2.1 在completedBlock里傳入error
[self callCompletionBlockForOperation:strongOperation completion:completedBlock error:error url:url];
//2.2 在錯(cuò)誤url名單中添加當(dāng)前的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 {
//3. 下載成功
//3.1 如果需要下載失敗后重新下載硼啤,則將當(dāng)前url從失敗url名單里移除
if ((options & SDWebImageRetryFailed)) {
@synchronized (self.failedURLs) {
[self.failedURLs removeObject:url];
}
}
//3.2 進(jìn)行緩存
BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
if (options & SDWebImageRefreshCached && cachedImage && !downloadedImage) {
//(即使緩存存在,也要刷新圖片) && 緩存圖片 && 不存在下載后的圖片:不做操作
} else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
//(下載圖片成功 && (沒有動(dòng)圖||處理動(dòng)圖) && (下載之后斧账,緩存之前處理圖片) 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];
}
//將圖片傳入completedBlock
[self callCompletionBlockForOperation:strongOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
});
} else {
//(圖片下載成功并結(jié)束)
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];
}
}
//如果完成谴返,從當(dāng)前運(yùn)行的操作列表里移除當(dāng)前操作
if (finished) {
[self safelyRemoveOperationFromRunning:strongOperation];
}
}];
//取消的block
operation.cancelBlock = ^{
//取消當(dāng)前的token
[self.imageDownloader cancel:subOperationToken];
__strong __typeof(weakOperation) strongOperation = weakOperation;
//從當(dāng)前運(yùn)行的操作列表里移除當(dāng)前操作
[self safelyRemoveOperationFromRunning:strongOperation];
};
} else if (cachedImage) {
//存在緩存圖片
__strong __typeof(weakOperation) strongOperation = weakOperation;
//調(diào)用完成的block
[self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
//刪去當(dāng)前的的下載操作(線程安全)
[self safelyRemoveOperationFromRunning:operation];
} else {
//沒有緩存的圖片,而且下載被代理終止了
__strong __typeof(weakOperation) strongOperation = weakOperation;
// 調(diào)用完成的block
[self callCompletionBlockForOperation:strongOperation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url];
//刪去當(dāng)前的下載操作
[self safelyRemoveOperationFromRunning:operation];
}
}];
return operation;
}
看完了SDWebImageManager
的回調(diào)處理咧织,我們分別看一下
SDImageCache
和SDWebImageDownloader
內(nèi)部具體是如何工作的嗓袱。首先看一下SDImageCache
:
SDImageCache
屬性
// ============== SDImageCache.m ============== //
@property (strong, nonatomic, nonnull) NSCache *memCache;//內(nèi)存緩存
@property (strong, nonatomic, nonnull) NSString *diskCachePath;//磁盤緩存路徑
@property (strong, nonatomic, nullable) NSMutableArray<NSString *> *customPaths;//
@property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t //ioQueue唯一子線程;
核心方法:查詢緩存
// ============== SDImageCache.m ============== //
- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock {
if (!key) {
if (doneBlock) {
doneBlock(nil, nil, SDImageCacheTypeNone);
}
return nil;
}
//================查看內(nèi)存的緩存=================//
UIImage *image = [self imageFromMemoryCacheForKey:key];
// 如果存在,直接調(diào)用block习绢,將image渠抹,data,CaheType傳進(jìn)去
if (image) {
NSData *diskData = nil;
//如果是gif闪萄,就拿到data梧却,后面要傳到doneBlock里。不是gif就傳nil
if ([image isGIF]) {
diskData = [self diskImageDataBySearchingAllPathsForKey:key];
}
if (doneBlock) {
doneBlock(image, diskData, SDImageCacheTypeMemory);
}
//因?yàn)閳D片有緩存可供使用桃煎,所以不用實(shí)例化NSOperation,直接范圍nil
return nil;
}
//================查看磁盤的緩存=================//
NSOperation *operation = [NSOperation new];
//唯一的子線程:self.ioQueue
dispatch_async(self.ioQueue, ^{
if (operation.isCancelled) {
// 在用之前就判斷operation是否被取消了大刊,作者考慮的非常嚴(yán)謹(jǐn)
return;
}
@autoreleasepool {
NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
UIImage *diskImage = [self diskImageForKey:key];
if (diskImage && self.config.shouldCacheImagesInMemory) {
// cost 被用來計(jì)算緩存中所有對(duì)象的代價(jià)为迈。當(dāng)內(nèi)存受限或者所有緩存對(duì)象的總代價(jià)超過了最大允許的值時(shí),緩存會(huì)移除其中的一些對(duì)象缺菌。
NSUInteger cost = SDCacheCostForImage(diskImage);
//存入內(nèi)存緩存中
[self.memCache setObject:diskImage forKey:key cost:cost];
}
if (doneBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
doneBlock(diskImage, diskData, SDImageCacheTypeDisk);
});
}
}
});
return operation;
}
SDWebImageDownloader
屬性
// ============== SDWebImageDownloader.m ============== //
@property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue;//下載隊(duì)列
@property (weak, nonatomic, nullable) NSOperation *lastAddedOperation;//最后添加的下載操作
@property (assign, nonatomic, nullable) Class operationClass;//操作類
@property (strong, nonatomic, nonnull) NSMutableDictionary<NSURL *, SDWebImageDownloaderOperation *> *URLOperations;//操作數(shù)組
@property (strong, nonatomic, nullable) SDHTTPHeadersMutableDictionary *HTTPHeaders;//HTTP請(qǐng)求頭
@property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t barrierQueue;//用來阻塞前面的下載線程(串行化)
核心方法:下載圖片
// ============== SDWebImageDownloader.m ============== //
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
options:(SDWebImageDownloaderOptions)options
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
__weak SDWebImageDownloader *wself = self;
return [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^SDWebImageDownloaderOperation *{
__strong __typeof (wself) sself = wself;
NSTimeInterval timeoutInterval = sself.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
//創(chuàng)建下載請(qǐng)求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
request.HTTPShouldUsePipelining = YES;
if (sself.headersFilter) {
request.allHTTPHeaderFields = sself.headersFilter(url, [sself.HTTPHeaders copy]);
}
else {
request.allHTTPHeaderFields = sself.HTTPHeaders;
}
//創(chuàng)建下載操作:SDWebImageDownloaderOperation用于請(qǐng)求網(wǎng)絡(luò)資源的操作葫辐,它是一個(gè) NSOperation 的子類
SDWebImageDownloaderOperation *operation = [[sself.operationClass alloc] initWithRequest:request inSession:sself.session options:options];
operation.shouldDecompressImages = sself.shouldDecompressImages;
//url證書
if (sself.urlCredential) {
operation.credential = sself.urlCredential;
} else if (sself.username && sself.password) {
operation.credential = [NSURLCredential credentialWithUser:sself.username password:sself.password persistence:NSURLCredentialPersistenceForSession];
}
//優(yōu)先級(jí)
if (options & SDWebImageDownloaderHighPriority) {
operation.queuePriority = NSOperationQueuePriorityHigh;
} else if (options & SDWebImageDownloaderLowPriority) {
operation.queuePriority = NSOperationQueuePriorityLow;
}
//在下載隊(duì)列里添加下載操作,執(zhí)行下載操作
[sself.downloadQueue addOperation:operation];
//如果后進(jìn)先出
if (sself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
// Emulate LIFO execution order by systematically adding new operations as last operation's dependency
//addDependency:參數(shù)opertaion倍添加到NSOperationQueue后伴郁,只有等該opertion結(jié)束后才能執(zhí)行其他的operation耿战,實(shí)現(xiàn)了后進(jìn)先出
[sself.lastAddedOperation addDependency:operation];
sself.lastAddedOperation = operation;
}
return operation;
}];
}
這里面還有一個(gè)addProgressCallback: progressBlock: completedBlock: forURL: createCallback:
方法,用來保存progressBlock
和completedBlock
焊傅。我們看一下這個(gè)方法的實(shí)現(xiàn):
// ============== SDWebImageDownloader.m ============== //
- (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock
completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock
forURL:(nullable NSURL *)url
createCallback:(SDWebImageDownloaderOperation *(^)())createCallback {
// url 用來作為回調(diào)字典的key剂陡,如果為空狈涮,立即返回失敗
if (url == nil) {
if (completedBlock != nil) {
completedBlock(nil, nil, nil, NO);
}
return nil;
}
__block SDWebImageDownloadToken *token = nil;
//串行化前面所有的操作
dispatch_barrier_sync(self.barrierQueue, ^{
//當(dāng)前下載操作中取出SDWebImageDownloaderOperation實(shí)例
SDWebImageDownloaderOperation *operation = self.URLOperations[url];
if (!operation) {
//如果沒有,就初始化它
operation = createCallback();
self.URLOperations[url] = operation;
__weak SDWebImageDownloaderOperation *woperation = operation;
operation.completionBlock = ^{
SDWebImageDownloaderOperation *soperation = woperation;
if (!soperation) return;
if (self.URLOperations[url] == soperation) {
[self.URLOperations removeObjectForKey:url];
};
};
}
id downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock];
//這里 downloadOperationCancelToken 默認(rèn)是一個(gè)字典鸭栖,存放 progressBlock 和 completedBlock
token = [SDWebImageDownloadToken new];
token.url = url;
token.downloadOperationCancelToken = downloadOperationCancelToken;
});
return token;
}
這里真正保存兩個(gè)block的方法是addHandlersForProgress: completed:
:
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
//實(shí)例化一個(gè)SDCallbacksDictionary歌馍,存放一個(gè)progressBlock 和 completedBlock
SDCallbacksDictionary *callbacks = [NSMutableDictionary new];
if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
dispatch_barrier_async(self.barrierQueue, ^{
//添加到緩存中 self.callbackBlocks
[self.callbackBlocks addObject:callbacks];
});
return callbacks;
}
到這里SDWebImage
的核心方法都講解完畢了,其他沒有講到的部分以后會(huì)慢慢添加上去晕鹊。
最后看一下一些比較零散的知識(shí)點(diǎn):
1. 運(yùn)行時(shí)存取關(guān)聯(lián)對(duì)象:
存:
objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//將operations對(duì)象關(guān)聯(lián)給self松却,地址為&loadOperationKey,語(yǔ)義是OBJC_ASSOCIATION_RETAIN_NONATOMIC溅话。
认汀:
SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
//將operations對(duì)象通過地址&loadOperationKey從self里取出來
2. 數(shù)組的寫操作需要加鎖(多線程訪問,避免覆寫)
//給self.runningOperations加鎖
//self.runningOperations數(shù)組的添加操作
@synchronized (self.runningOperations) {
[self.runningOperations addObject:operation];
}
//self.runningOperations數(shù)組的刪除操作
- (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
@synchronized (self.runningOperations) {
if (operation) {
[self.runningOperations removeObject:operation];
}
}
}
3. 確保在主線程的宏:
dispatch_main_async_safe(^{
//將下面這段代碼放在主線程中
[self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock];
});
//宏定義:
#define dispatch_main_async_safe(block)\
if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
#endif
4. 設(shè)置不能為nil的參數(shù)
- (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;
}
如果在參數(shù)里添加了nonnull關(guān)鍵字飞几,那么編譯器就可以檢查傳入的參數(shù)是否為nil砚哆,如果是,則編譯器會(huì)有警告
5. 容錯(cuò)循狰,強(qiáng)制轉(zhuǎn)換類型
if ([url isKindOfClass:NSString.class]) {
url = [NSURL URLWithString:(NSString *)url];
}
在傳入的參數(shù)為NSString時(shí)(但是方法參數(shù)要求是NSURL)窟社,自動(dòng)轉(zhuǎn)換為NSURL
貌似還有圖片解碼等內(nèi)容沒有詳細(xì)看,以后會(huì)逐漸補(bǔ)充噠~
本文已經(jīng)同步到我的個(gè)人技術(shù)博客:傳送門绪钥,歡迎常來^^
本文已在版權(quán)印備案灿里,如需轉(zhuǎn)載請(qǐng)?jiān)L問版權(quán)印。48422928
-------------------------------- 2018年7月17日更新 --------------------------------
注意注意3谈埂O坏酢!
筆者在近期開通了個(gè)人公眾號(hào)寸潦,主要分享編程色鸳,讀書筆記,思考類的文章见转。
- 編程類文章:包括筆者以前發(fā)布的精選技術(shù)文章命雀,以及后續(xù)發(fā)布的技術(shù)文章(以原創(chuàng)為主),并且逐漸脫離 iOS 的內(nèi)容斩箫,將側(cè)重點(diǎn)會(huì)轉(zhuǎn)移到提高編程能力的方向上吏砂。
- 讀書筆記類文章:分享編程類,思考類乘客,心理類狐血,職場(chǎng)類書籍的讀書筆記。
- 思考類文章:分享筆者平時(shí)在技術(shù)上易核,生活上的思考匈织。
因?yàn)楣娞?hào)每天發(fā)布的消息數(shù)有限制,所以到目前為止還沒有將所有過去的精選文章都發(fā)布在公眾號(hào)上,后續(xù)會(huì)逐步發(fā)布的缀匕。
而且因?yàn)楦鞔蟛┛推脚_(tái)的各種限制纳决,后面還會(huì)在公眾號(hào)上發(fā)布一些短小精干,以小見大的干貨文章哦~
掃下方的公眾號(hào)二維碼并點(diǎn)擊關(guān)注弦追,期待與您的共同成長(zhǎng)~