第九篇

前言

SDWebImageManagerSDWebImage中最核心的类了,但是源代码确是非常简单的。之所以能做到这一点,都归功于功能的良好分类。

有了SDWebImageManager这个基石,我们就能做很多其他的有意思的事情。比如给各种view绑定一个URL,就能显示图片的功能,有了Options,就能满足多种应用场景的图片下载任务。

读源码既能让我们更好地使用该框架,又能让我们学到很多知识,还能让我们懂得如何去扩充现有的功能。

SDWebImageOptions

SDWebImageOptions作为下载的选项提供了非常多的子项,用法和注意事项我都写在代码的注释中了:

  1. typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
  2. /**
  3. * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.
  4. * This flag disable this blacklisting.
  5. */
  6. /// 每一个下载都会提供一个URL,如果这个URL是错误,SD就会把它放入到黑名单之中,
  7. /// 黑名单中的URL是不会再次进行下载的,但是,当设置了该选项时,SD会将其在黑名单中移除,重新下载该URL,
  8. SDWebImageRetryFailed = 1 << 0,
  9. /**
  10. * By default, image downloads are started during UI interactions, this flags disable this feature,
  11. * leading to delayed download on UIScrollView deceleration for instance.
  12. */
  13. /// 一般来说,下载都是按照一定的先后顺序开始的,但是该选项能够延迟下载,也就说他的权限比较低,权限比他高的在他前边下载
  14. SDWebImageLowPriority = 1 << 1,
  15. /**
  16. * This flag disables on-disk caching
  17. */
  18. /// 该选项要求SD只把图片缓存到内存中,不缓存到disk中
  19. SDWebImageCacheMemoryOnly = 1 << 2,
  20. /**
  21. * This flag enables progressive download, the image is displayed progressively during download as a browser would do.
  22. * By default, the image is only displayed once completely downloaded.
  23. */
  24. /// 给下载添加进度
  25. SDWebImageProgressiveDownload = 1 << 3,
  26. /**
  27. * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
  28. * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
  29. * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.
  30. * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.
  31. *
  32. * Use this flag only if you can't make your URLs static with embedded cache busting parameter.
  33. */
  34. /// 有这么一种使用场景,如果一个图片的资源发生了改变。但是url并没有变,我们就可以使用该选项来刷新数据了
  35. SDWebImageRefreshCached = 1 << 4,
  36. /**
  37. * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
  38. * extra time in background to let the request finish. If the background task expires the operation will be cancelled.
  39. */
  40. /// 支持切换到后台也能下载
  41. SDWebImageContinueInBackground = 1 << 5,
  42. /**
  43. * Handles cookies stored in NSHTTPCookieStore by setting
  44. * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
  45. */
  46. /// 使用Cookies
  47. SDWebImageHandleCookies = 1 << 6,
  48. /**
  49. * Enable to allow untrusted SSL certificates.
  50. * Useful for testing purposes. Use with caution in production.
  51. */
  52. /// 允许验证证书
  53. SDWebImageAllowInvalidSSLCertificates = 1 << 7,
  54. /**
  55. * By default, images are loaded in the order in which they were queued. This flag moves them to
  56. * the front of the queue.
  57. */
  58. /// 高权限
  59. SDWebImageHighPriority = 1 << 8,
  60. /**
  61. * By default, placeholder images are loaded while the image is loading. This flag will delay the loading
  62. * of the placeholder image until after the image has finished loading.
  63. */
  64. /// 一般情况下,placeholder image 都会在图片下载完成前显示,该选项将设置placeholder image在下载完成之后才能显示
  65. SDWebImageDelayPlaceholder = 1 << 9,
  66. /**
  67. * We usually don't call transformDownloadedImage delegate method on animated images,
  68. * as most transformation code would mangle it.
  69. * Use this flag to transform them anyway.
  70. */
  71. /// 使用该属性来自由改变图片,但需要使用transformDownloadedImage delegate
  72. SDWebImageTransformAnimatedImage = 1 << 10,
  73. /**
  74. * By default, image is added to the imageView after download. But in some cases, we want to
  75. * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance)
  76. * Use this flag if you want to manually set the image in the completion when success
  77. */
  78. /// 该选项允许我们在图片下载完成后不会立刻给view设置图片,比较常用的使用场景是给赋值的图片添加动画
  79. SDWebImageAvoidAutoSetImage = 1 << 11,
  80. /**
  81. * By default, images are decoded respecting their original size. On iOS, this flag will scale down the
  82. * images to a size compatible with the constrained memory of devices.
  83. * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated.
  84. */
  85. /// 压缩大图片
  86. SDWebImageScaleDownLargeImages = 1 << 12
  87. };

Block

  1. typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL);
  2. typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL);
  3. typedef NSString * _Nullable (^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable url);

我们在平时的开发中,使用Block可以参考上边的使用方法,XXXxxxCompletionBlock这种命名应该是Apple的风格。

SDWebImageManagerDelegate

使用协议增加了我们编程的灵活性,SDWebImageManagerDelegate提供了两个方法

  • 在缓存中没发现图片,控制是不是下载该图片
  • 自由转换图片

代码:

  1. @protocol SDWebImageManagerDelegate <NSObject>
  2. @optional
  3. /**
  4. * Controls which image should be downloaded when the image is not found in the cache.
  5. *
  6. * @param imageManager The current `SDWebImageManager`
  7. * @param imageURL The url of the image to be downloaded
  8. *
  9. * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
  10. */
  11. - (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nullable NSURL *)imageURL;
  12. /**
  13. * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
  14. * NOTE: This method is called from a global queue in order to not to block the main thread.
  15. *
  16. * @param imageManager The current `SDWebImageManager`
  17. * @param image The image to transform
  18. * @param imageURL The url of the image to transform
  19. *
  20. * @return The transformed image object.
  21. */
  22. - (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable NSURL *)imageURL;
  23. @end

SDWebImageCombinedOperation

SDWebImageCombinedOperation是对每一个下载任务的封装,重要的是它提供了一个取消功能。

  1. @interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
  2. @property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
  3. @property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock;
  4. @property (strong, nonatomic, nullable) NSOperation *cacheOperation;
  5. @end

SDWebImageManager

1.属性

  1. @interface SDWebImageManager ()
  2. @property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache;
  3. @property (strong, nonatomic, readwrite, nonnull) SDWebImageDownloader *imageDownloader;
  4. @property (strong, nonatomic, nonnull) NSMutableSet<NSURL *> *failedURLs;
  5. @property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageCombinedOperation *> *runningOperations;
  6. @end

2.初始化(非常典型的初始化)

  1. + (nonnull instancetype)sharedManager {
  2. static dispatch_once_t once;
  3. static id instance;
  4. dispatch_once(&once, ^{
  5. instance = [self new];
  6. });
  7. return instance;
  8. }
  9. - (nonnull instancetype)init {
  10. SDImageCache *cache = [SDImageCache sharedImageCache];
  11. SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
  12. return [self initWithCache:cache downloader:downloader];
  13. }
  14. - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader {
  15. if ((self = [super init])) {
  16. _imageCache = cache;
  17. _imageDownloader = downloader;
  18. _failedURLs = [NSMutableSet new];
  19. _runningOperations = [NSMutableArray new];
  20. }
  21. return self;
  22. }

3.URL => key

  1. - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
  2. if (!url) {
  3. return @"";
  4. }
  5. if (self.cacheKeyFilter) {
  6. return self.cacheKeyFilter(url);
  7. } else {
  8. return url.absoluteString;
  9. }
  10. }

4.查看图片是否已经缓存

现在内容中读取,没有的话再去disk读取。

  1. - (void)cachedImageExistsForURL:(nullable NSURL *)url
  2. completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
  3. NSString *key = [self cacheKeyForURL:url];
  4. BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil);
  5. if (isInMemoryCache) {
  6. // making sure we call the completion block on the main queue
  7. dispatch_async(dispatch_get_main_queue(), ^{
  8. if (completionBlock) {
  9. completionBlock(YES);
  10. }
  11. });
  12. return;
  13. }
  14. [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
  15. // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
  16. if (completionBlock) {
  17. completionBlock(isInDiskCache);
  18. }
  19. }];
  20. }

5.查看是否已经缓存到了硬盘

  1. - (void)diskImageExistsForURL:(nullable NSURL *)url
  2. completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
  3. NSString *key = [self cacheKeyForURL:url];
  4. [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
  5. // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
  6. if (completionBlock) {
  7. completionBlock(isInDiskCache);
  8. }
  9. }];
  10. }

6.核心下载方法

对于一个比较复杂的函数,我们往往只需要左下边三件事就可以了:

  • 处理参数相关的异常
  • 处理复杂的逻辑
  • 返回数据

这三条适合所有的函数,由于这个方法的逻辑比较复杂,我把详细的注释都写到代码中了

  1. - (id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
  2. options:(SDWebImageOptions)options
  3. progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
  4. completed:(nullable SDInternalCompletionBlock)completedBlock {
  5. // Invoking this method without a completedBlock is pointless
  6. /// 1.如果想预先下载图片,使用[SDWebImagePrefetcher prefetchURLs]取代本方法
  7. /// 预下载图片是有很多种使用场景的,当我们使用SDWebImagePrefetcher下载图片后,之后使用该图片时就不用再网络上下载了。
  8. NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead");
  9. // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't
  10. // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
  11. /// 2.XCode有时候经常会犯一些错误,当用户给url赋值了字符串的时候,XCode也没有报错,因此这里提供一种
  12. /// 错误修正的处理。
  13. if ([url isKindOfClass:NSString.class]) {
  14. url = [NSURL URLWithString:(NSString *)url];
  15. }
  16. // Prevents app crashing on argument type error like sending NSNull instead of NSURL
  17. /// 3.防止参数的其他错误
  18. if (![url isKindOfClass:NSURL.class]) {
  19. url = nil;
  20. }
  21. /// 4.operation会被作为该方法的返回值,但operation的类型是SDWebImageCombinedOperation,是一个封装的对象,并不是一个NSOperation
  22. __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
  23. __weak SDWebImageCombinedOperation *weakOperation = operation;
  24. /// 5.在图片的下载中,会有一些下载失败的情况,这时候我们把这些下载失败的url放到一个集合中去,
  25. /// 也就是加入了黑名单中,默认是不会再继续下载黑名单中的url了,但是也有例外,当options被设置为
  26. /// SDWebImageRetryFailed的时候,会尝试进行重新下载。
  27. BOOL isFailedUrl = NO;
  28. if (url) {
  29. @synchronized (self.failedURLs) {
  30. isFailedUrl = [self.failedURLs containsObject:url];
  31. }
  32. }
  33. /// 6.会有两种情况让我们停止下载这个rul指定的图片:
  34. /// - url的长度为0
  35. /// - options并没有选择SDWebImageRetryFailed(重新下载错误url)且这个url在黑名单之中
  36. /// 调用完成Block,返回operation
  37. if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
  38. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url];
  39. return operation;
  40. }
  41. /// 7.排除了所有的错误可能后,我们就先把这个operation添加到正在运行操作的数组中
  42. /// 这里没有判断self.runningOperations是不是包含了operation,
  43. /// 说明肯定会在下边的代码中做判断,如果存在就删除operation
  44. @synchronized (self.runningOperations) {
  45. [self.runningOperations addObject:operation];
  46. }
  47. NSString *key = [self cacheKeyForURL:url];
  48. /// 8.self.imageCache的queryCacheOperationForKey方法是异步的获取指定key的图片,
  49. /// 但是这个方法的operation是同步返回的,也就是说下边的代码会直接执行到return那里。
  50. operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
  51. /// (8.1).这个Block会在查询完指定的key的图片后调用,由` dispatch_async(self.ioQueue, ^{`
  52. /// 这个可以看出,实在异步线程采用串行的方式在调用,任务在self.imageCache的ioQueue中一个一个执行,是线程安全的
  53. /// (8.2).如果每次调用loadImage方法都会生成一个operation,如果我们想取消某个下载任务
  54. /// 再设计上来说,只要把响应的operation.isCancelled设置为NO,那么下载就会被取消。
  55. if (operation.isCancelled) {
  56. [self safelyRemoveOperationFromRunning:operation];
  57. return;
  58. }
  59. /// (8.3).代码来到这里,我们就要根据是否有缓存的图片来做出响应的处理
  60. /// 如果没有获取到缓存图片或者需要刷新缓存图片我们应该通过网络获取图片,但是这里增加了一个额外的控制
  61. /// 根据delegate的imageManager:shouldDownloadImageForURL:获取是否下载的权限,返回YES,就继续下载
  62. if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
  63. /// (8.3.1).这里需要注意了,当图片已经下载了,Options又选择了SDWebImageRefreshCached
  64. /// 就会触发一次completionBlock回调,这说明这个下载的回调不是只触发一次的
  65. /// 如果使用了dispatch_group_enter和dispatch_group_leave就一定要注意了
  66. if (cachedImage && options & SDWebImageRefreshCached) {
  67. // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image
  68. // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
  69. [self callCompletionBlockForOperation:weakOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
  70. }
  71. // download if no image or requested to refresh anyway, and download allowed by delegate
  72. /// (8.3.2).这里是SDWebImageOptions到SDWebImageDownloaderOptions的转换
  73. /// 其实就是0 |= xxx
  74. SDWebImageDownloaderOptions downloaderOptions = 0;
  75. if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
  76. if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload;
  77. if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache;
  78. if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
  79. if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
  80. if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
  81. if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority;
  82. if (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages;
  83. /// (8.3.3).已经缓存且SDWebImageRefreshCached的比较特殊
  84. if (cachedImage && options & SDWebImageRefreshCached) {
  85. // force progressive off if image already cached but forced refreshing
  86. /// (8.3.3.1).SDWebImageDownloaderProgressiveDownload为 1<<1 ,
  87. /*
  88. 由于当options == SDWebImageRefreshCached时,downloaderOptions |= SDWebImageDownloaderUseNSURLCache(1 << 2)
  89. 00000000 | 00000100 => 00000100
  90. ~SDWebImageDownloaderProgressiveDownload : ~ 00000010 => 111111101
  91. 00000100 & 11111101 => 00000100
  92. */
  93. downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
  94. // ignore image read from NSURLCache if image if cached but force refreshing
  95. /// (8.3.3.2). 00000100 | 00001000 => 00001100
  96. /// 通过这种位的运算,就能够给同一个值赋值两种转态
  97. downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
  98. }
  99. /// (8.3.4).下载图片
  100. SDWebImageDownloadToken *subOperationToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {
  101. __strong __typeof(weakOperation) strongOperation = weakOperation;
  102. if (!strongOperation || strongOperation.isCancelled) {
  103. // Do nothing if the operation was cancelled
  104. // See #699 for more details
  105. // 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
  106. } else if (error) {
  107. /// (8.3.4.1).发生错误就返回
  108. [self callCompletionBlockForOperation:strongOperation completion:completedBlock error:error url:url];
  109. /// (8.3.4.2).除了下边这几种情况之外的情况则把url加入黑名单
  110. if ( error.code != NSURLErrorNotConnectedToInternet
  111. && error.code != NSURLErrorCancelled
  112. && error.code != NSURLErrorTimedOut
  113. && error.code != NSURLErrorInternationalRoamingOff
  114. && error.code != NSURLErrorDataNotAllowed
  115. && error.code != NSURLErrorCannotFindHost
  116. && error.code != NSURLErrorCannotConnectToHost) {
  117. @synchronized (self.failedURLs) {
  118. [self.failedURLs addObject:url];
  119. }
  120. }
  121. }
  122. else {
  123. /// (8.3.4.3).如果是SDWebImageRetryFailed就在黑名单中移除,不管有没有
  124. if ((options & SDWebImageRetryFailed)) {
  125. @synchronized (self.failedURLs) {
  126. [self.failedURLs removeObject:url];
  127. }
  128. }
  129. BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
  130. if (options & SDWebImageRefreshCached && cachedImage && !downloadedImage) {
  131. // Image refresh hit the NSURLCache cache, do not call the completion block
  132. } else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { // 要不要修改图片,这个修改图片完全由代理来操作
  133. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  134. UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
  135. if (transformedImage && finished) {
  136. BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
  137. // pass nil if the image was transformed, so we can recalculate the data from the image
  138. [self.imageCache storeImage:transformedImage imageData:(imageWasTransformed ? nil : downloadedData) forKey:key toDisk:cacheOnDisk completion:nil];
  139. }
  140. [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
  141. });
  142. } else {
  143. if (downloadedImage && finished) {
  144. [self.imageCache storeImage:downloadedImage imageData:downloadedData forKey:key toDisk:cacheOnDisk completion:nil];
  145. }
  146. [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:downloadedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
  147. }
  148. }
  149. /// (8.3.4.4).完成了就把该任务在正运行着的数组中删除
  150. if (finished) {
  151. [self safelyRemoveOperationFromRunning:strongOperation];
  152. }
  153. }];
  154. /// (8.3.5).设置取消的回调
  155. operation.cancelBlock = ^{
  156. [self.imageDownloader cancel:subOperationToken];
  157. __strong __typeof(weakOperation) strongOperation = weakOperation;
  158. [self safelyRemoveOperationFromRunning:strongOperation];
  159. };
  160. } else if (cachedImage) {
  161. __strong __typeof(weakOperation) strongOperation = weakOperation;
  162. [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
  163. [self safelyRemoveOperationFromRunning:operation];
  164. } else {
  165. // Image not in cache and download disallowed by delegate
  166. /// (8.4).既没有缓存也下载了代理不允许的图片
  167. __strong __typeof(weakOperation) strongOperation = weakOperation;
  168. [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url];
  169. [self safelyRemoveOperationFromRunning:operation];
  170. }
  171. }];
  172. return operation;
  173. }

7.保存图片到缓存区

  1. - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url {
  2. if (image && url) {
  3. NSString *key = [self cacheKeyForURL:url];
  4. [self.imageCache storeImage:image forKey:key toDisk:YES completion:nil];
  5. }
  6. }

8.取消所有的下载

  1. - (void)cancelAll {
  2. @synchronized (self.runningOperations) {
  3. NSArray<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy];
  4. [copiedOperations makeObjectsPerformSelector:@selector(cancel)];
  5. [self.runningOperations removeObjectsInArray:copiedOperations];
  6. }
  7. }

9.查看是否下载完毕

  1. - (BOOL)isRunning {
  2. BOOL isRunning = NO;
  3. @synchronized (self.runningOperations) {
  4. isRunning = (self.runningOperations.count > 0);
  5. }
  6. return isRunning;
  7. }

10.安全移除任务

要想安全的操作数组,只要给数组本身加个锁就行了,但@synchronized的性能不是很好

  1. - (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
  2. @synchronized (self.runningOperations) {
  3. if (operation) {
  4. [self.runningOperations removeObject:operation];
  5. }
  6. }
  7. }

11.回调

  1. - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
  2. completion:(nullable SDInternalCompletionBlock)completionBlock
  3. error:(nullable NSError *)error
  4. url:(nullable NSURL *)url {
  5. [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES url:url];
  6. }
  7. - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
  8. completion:(nullable SDInternalCompletionBlock)completionBlock
  9. image:(nullable UIImage *)image
  10. data:(nullable NSData *)data
  11. error:(nullable NSError *)error
  12. cacheType:(SDImageCacheType)cacheType
  13. finished:(BOOL)finished
  14. url:(nullable NSURL *)url {
  15. dispatch_main_async_safe(^{
  16. if (operation && !operation.isCancelled && completionBlock) {
  17. completionBlock(image, data, error, cacheType, finished, url);
  18. }
  19. });
  20. }

12.SDWebImageCombinedOperation实现方法

  1. - (void)setCancelBlock:(nullable SDWebImageNoParamsBlock)cancelBlock {
  2. // check if the operation is already cancelled, then we just call the cancelBlock
  3. if (self.isCancelled) {
  4. if (cancelBlock) {
  5. cancelBlock();
  6. }
  7. _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes
  8. } else {
  9. _cancelBlock = [cancelBlock copy];
  10. }
  11. }
  12. - (void)cancel {
  13. self.cancelled = YES;
  14. if (self.cacheOperation) {
  15. [self.cacheOperation cancel];
  16. self.cacheOperation = nil;
  17. }
  18. if (self.cancelBlock) {
  19. self.cancelBlock();
  20. // TODO: this is a temporary fix to #809.
  21. // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
  22. // self.cancelBlock = nil;
  23. _cancelBlock = nil;
  24. }
  25. }

总结

SD的源码读了大部分了,也收获很大,现在写代码的风格也越来越靠近这种框架风格,我们应该为写出的每一个函数负责。

在上一篇SDWebImage源码解读之SDWebImageDownloader的评论区,有小伙伴提出了SD在特定使用场景会崩溃的情况,我也做了一些实验。

  1. - (void)test {
  2. NSURL *url = [NSURL URLWithString:@"//upload-images.jianshu.io/upload_images/1432482-dcc38746f56a89ab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"];
  3. SDWebImageManager *manager = [SDWebImageManager sharedManager];
  4. dispatch_group_t group = dispatch_group_create();
  5. dispatch_group_enter(group);
  6. [manager loadImageWithURL:url options:SDWebImageRefreshCached progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
  7. dispatch_group_leave(group);
  8. }];
  9. dispatch_group_notify(group, dispatch_get_main_queue(), ^{
  10. NSLog(@"下载完成了");
  11. });
  12. }

在上边的函数中,我使用了dispatch_group_t dispatch_group_enter dispatch_group_leave 目的是等待所有的异步任务完成。

enter和leave方法必须成对出现,如果调用leave的次数多于enter就会崩溃,当我们使用SD时,如果Options设置为SDWebImageRefreshCached,那么这个completionBlock至少会调用两次,首先返回缓存中的图片。其次在下载完成后再次调用Block,这也就是崩溃的原因。

要想重现上边方法的崩溃,等图片下载完之后,再从新调用该方法就行。

SD默认下载的图片会缓存进内存和disk中。

由于个人知识有限,如有错误之处,还望各路大侠给予指出啊

  1. SDWebImage源码解读 之 NSData+ImageContentType 简书 博客园
  2. SDWebImage源码解读 之 UIImage+GIF 简书 博客园
  3. SDWebImage源码解读 之 SDWebImageCompat 简书 博客园
  4. SDWebImage源码解读 之SDWebImageDecoder 简书 博客园
  5. SDWebImage源码解读 之SDWebImageCache(上) 简书 博客园
  6. SDWebImage源码解读之SDWebImageCache(下) 简书 博客园
  7. SDWebImage源码解读之SDWebImageDownloaderOperation 简书 博客园
  8. SDWebImage源码解读之SDWebImageDownloader 简书 博客园

SDWebImage源码解读之SDWebImageManager的更多相关文章

  1. SDWebImage源码解读之SDWebImagePrefetcher

    > 第十篇 ## 前言 我们先看看`SDWebImage`主文件的组成模块: ![](http://images2015.cnblogs.com/blog/637318/201701/63731 ...

  2. SDWebImage源码解读之分类

    第十一篇 前言 我们知道SDWebImageManager是用来管理图片下载的,但我们平时的开发更多的是使用UIImageView和UIButton这两个控件显示图片. 按照正常的想法,我们只需要在他 ...

  3. SDWebImage源码解读之干货大总结

    这是我认为的一些重要的知识点进行的总结. 1.图片编码简介 大家都知道,数据在网络中是以二进制流的形式传播的,那么我们该如何把那些1和0解析成我们需要的数据格式呢? 说的简单一点就是,当文件都使用二进 ...

  4. SDWebImage源码解读之SDWebImageDownloaderOperation

    第七篇 前言 本篇文章主要讲解下载操作的相关知识,SDWebImageDownloaderOperation的主要任务是把一张图片从服务器下载到内存中.下载数据并不难,如何对下载这一系列的任务进行设计 ...

  5. SDWebImage源码解读 之 NSData+ImageContentType

    第一篇 前言 从今天开始,我将开启一段源码解读的旅途了.在这里先暂时不透露具体解读的源码到底是哪些?因为也可能随着解读的进行会更改计划.但能够肯定的是,这一系列之中肯定会有Swift版本的代码. 说说 ...

  6. SDWebImage源码解读 之 UIImage+GIF

    第二篇 前言 本篇是和GIF相关的一个UIImage的分类.主要提供了三个方法: + (UIImage *)sd_animatedGIFNamed:(NSString *)name ----- 根据名 ...

  7. SDWebImage源码解读 之 SDWebImageCompat

    第三篇 前言 本篇主要解读SDWebImage的配置文件.正如compat的定义,该配置文件主要是兼容Apple的其他设备.也许我们真实的开发平台只有一个,但考虑各个平台的兼容性,对于框架有着很重要的 ...

  8. SDWebImage源码解读_之SDWebImageDecoder

    第四篇 前言 首先,我们要弄明白一个问题? 为什么要对UIImage进行解码呢?难道不能直接使用吗? 其实不解码也是可以使用的,假如说我们通过imageNamed:来加载image,系统默认会在主线程 ...

  9. SDWebImage源码解读之SDWebImageCache(上)

    第五篇 前言 本篇主要讲解图片缓存类的知识,虽然只涉及了图片方面的缓存的设计,但思想同样适用于别的方面的设计.在架构上来说,缓存算是存储设计的一部分.我们把各种不同的存储内容按照功能进行切割后,图片缓 ...

随机推荐

  1. json转义字符串

    json前台写数据 @RequestMapping("/addUserJson") public void addUserJson(User user,HttpServletReq ...

  2. eclipse shortcut binding

    有些真的是太方便了,我竟然不知道,比如ctrl + h 就是打开search 功能,包括file search,我竟然每次都点击工具条上的放大镜图标! use Ctrl+Shift+T for ope ...

  3. File和byte[]转换

    http://blog.csdn.net/commonslok/article/details/9493531 public static byte[] File2byte(String filePa ...

  4. javascript svg 页面 loading

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. Struts2 JSP中将list,set ,Map传递到Action然后遍历(三十五) - 雲淡風輕 - ITeye技术网站

    1.使用Strut2的的集合对象:在jsp初始化action中的list然后提交到action2.使用Struts标签,实现多个用户同时注册(注意属性配置文件)3.pojo package com.s ...

  6. HDU 2498 Digits

    水题.题目这样定义的,另f(x)为x有几位,x[i]=f(x[i-1]); 求最小的i使得x[i]==x[i-1] #include<cstdio> #include<cstring ...

  7. html-div-css

    用CSS实现拉动滚动条时固定网页背景不动   body{        background-image: url(./inc/bgbk.jpg);        background-attachm ...

  8. vim vimgdb reg 编译安装

    在各种无法忍受下,还是决心自己编译安装一个vim.由于vimgdb for 7.3的patch一直有点问题,因此还是选择了vim7.2做为编译安装的版本.(1)获取vim7.2: http://www ...

  9. UITableView回调和table相关成员方法详解

    http://blog.csdn.net/kingsley_cxz/article/details/9123959 1.UITableView的datasource实现: //回调获取每个sectio ...

  10. lpc1768ADC使用

    Lpc1768内置有一个ad外设,该外设有八路复用输入,所以,可以同时接八路ad设备,同时还支持触发转换模式,由外部端口进行ad触发,ad转换完成之后可以产生中断 Lpc1768支持的转换模式有两种, ...