美文网首页
SDWebImage源码简要解析

SDWebImage源码简要解析

作者: HearnWING | 来源:发表于2017-02-17 15:09 被阅读47次

    前言: SDWebImage是一个设计和编写都非常精妙的一个库,源码读下来非常的有收获。总体上运用了runtime, gcd的串行和并发队列,dispatch_barrier_async,NSOperation,NSOperationQueue ,autoreleasepool,NSCache实现内存缓存等。对多线程的使用,锁的使用,block的回调,内存优化,后台运行任务都是非常好的使用案例。

    - (void)sd_setImageWithURL:(NSURL *)url 之后的操作

    1. [self sd_cancelCurrentImageLoad];
      获取绑定在UIView上的Dictionary中以”UIImageViewImageLoad”key获取的所有 <SDWebImageOperation> ,并取消下载

    2. 将url绑定到该imageview上

    3. 如果有占位图片,在主线程设置图片

       __weak __typeof(self)wself = self; 
       if (!wself) return;
               dispatch_main_sync_safe(^{
                   if (!wself) return;
                   if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock)
                   {
                       completedBlock(image, error, cacheType, url);
                       return;
                   }
                   else if (image) {
                       wself.image = image;
                       [wself setNeedsLayout];
                   }
      

      }
      设置弱引用,并反复检查,设置后调用 [wself setNeedsLayout];
      重新调整子视图。

    4. 通过SDWebImageManager.sharedManager 创建一个 id <SDWebImageOperation> operation下载图片,以block回调并设置图片。并且将operation通过”UIImageViewImageLoad”key绑定。

    5. 下载过程
      创建一个 SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
      检查url是否在failedURLs里 @synchronized (self.failedURLs) {},如果在则执行下载失败block并返回

     @synchronized (self.runningOperations) {
            [self.runningOperations addObject:operation];
        } 添加operation到下载队列
    

    查询缓存中是否存在该图片,如果有则返回,并从队列中移除operation,在返回图片前要检查operation是否被取消,如果取消说明url变了,显然不能再被返回。查询缓存会新建一个operation并返回。

     NSOperation *operation = [NSOperation new];
        dispatch_async(self.ioQueue, ^{  //self.ioQueue是一个串行queue
            if (operation.isCancelled) {
                return;
            }
    //autoreleasepool用于及时释放内存
            @autoreleasepool {
    //从文件中读取data并默认对图片进行解码,支持gif和webp格式,解码也是新建一个autoreleasepool
                UIImage *diskImage = [self diskImageForKey:key];
                if (diskImage && self.shouldCacheImagesInMemory) {
                    NSUInteger cost = SDCacheCostForImage(diskImage);
                    [self.memCache setObject:diskImage forKey:key cost:cost];
                }
    
                dispatch_async(dispatch_get_main_queue(), ^{
                    doneBlock(diskImage, SDImageCacheTypeDisk);
                });
            }
        });
    

    重点说一下 内存中的缓存,通过NSCache实现

    FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
        return image.size.height * image.size.width * image.scale * image.scale;
    }
     [self.memCache setObject:diskImage forKey:key cost:cost]
    self.memCache 是 AutoPurgeCache : NSCache, 会在系统内存报警时自动移除所有缓存。
    

    如果缓存中没有图片则进行下载:

          _downloadQueue = [NSOperationQueue new];
            _downloadQueue.maxConcurrentOperationCount = 6;
            _downloadQueue.name = @"com.hackemist.SDWebImageDownloader";
            _URLCallbacks = [NSMutableDictionary new];
            _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
            _downloadTimeout = 15.0;
    
    //新建一个operation
    SDWebImageDownloaderOperation : NSOperation <SDWebImageOperation, NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
    //执行下载
    - (void)start { }
    // 允许后台下载
     self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{
                    __strong __typeof (wself) sself = wself;
    
                    if (sself) {
                        [sself cancel];
    
                        [app endBackgroundTask:sself.backgroundTaskId];
                        sself.backgroundTaskId = UIBackgroundTaskInvalid;
                    }
                }];
     self.thread = [NSThread currentThread];
    - (void)cancel {
        @synchronized (self) {
            if (self.thread) {
                [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO];
            }
    //下载完回调
    __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);
                                                                }
    

    通过dispatch_barrier_sync来隔离并发队列中的读和写
    queue会等待正在执行的block的执行完毕再执行。所以在这点上就保证了我们的barrier block 只有它自己在执行。所有的在他之后提交的block会一直等待到这个barrier block 执行完再执行。需要特别注意的是,传入dispatch_barrier_async()函数的queue,必须是用dispatch_queue_create 创建的并发queue。如果是串行的queue或者是global concurrent queues ,这个函数就会变成 dispatch_async()了

    dispatch_barrier_sync(self.barrierQueue,block);
    

    对一个url进行下载时,通过将url加入一个以url为key的dict,如果已经存在,说明正在下载,则不会执行下载block,同时还有处理另外一个imageview请求同一个url的情况。下面的代码非常巧妙的处理这种情况:

     dispatch_barrier_sync(self.barrierQueue, ^{
            BOOL first = NO;
            if (!self.URLCallbacks[url]) {
                self.URLCallbacks[url] = [NSMutableArray new];
                first = YES;
            }
    
            // Handle single download of simultaneous download request for the same URL
            NSMutableArray *callbacksForURL = self.URLCallbacks[url];
            NSMutableDictionary *callbacks = [NSMutableDictionary new];
    //将回调copy并存起来
            if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
            if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
    // 加入回调数组中
            [callbacksForURL addObject:callbacks];
            self.URLCallbacks[url] = callbacksForURL;
    
            if (first) {
                createCallback();
            }
        });
    

    如果设置了operationQueue的LIFO,对operation添加依赖

    if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
                // Emulate LIFO execution order by systematically adding new operations as last operation's dependency,The receiver is not considered ready to execute until all of its dependent operations have finished executing. If the receiver is already executing its task, adding dependencies has no practical effect. This method may change the isReady and dependencies properties of the receiver.如果已经在执行则无效,还没执行,要等依赖执行完之后才会被执行。
                [wself.lastAddedOperation addDependency:operation];
                wself.lastAddedOperation = operation;
            }
    

    相关文章

      网友评论

          本文标题:SDWebImage源码简要解析

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