iOS专题ios面试题整理

第三方库SDWebImage原理浅析

2016-11-28  本文已影响90人  一剑孤城

前言
SDWebImage是一个很受欢迎的图片缓存第三方库,使用十分方便,只需一行代码就可以实现设置占位图以及在网络图片拉取成功后替换占位图的功能。虽然,乍一看只是现实了拉取网络图片的小小功能,但是,里面还包含了很多逻辑代码,也是很复杂的。下面我主要讲的是关于设置网络图片的一些逻辑代码的实现,有关其它的功能(比如:图片缓存,图片下载线程的实现等等)一概不讨论。

1.SDWebImage库整体工作流程

具体逻辑如下图:


SDWebImage.PNG

2.下面详细说明这个流程所用到的函数

//通过key(一般都是url)获取下载线程
- (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
    // Cancel in progress downloader from queue
    NSMutableDictionary *operationDictionary = [self operationDictionary];    //获取下载队列字典
    id operations = [operationDictionary objectForKey:key];    //取出当前key的所有队列
    ···
    [operation cancel];    //取消当前线程
    ···
    [operationDictionary removeObjectForKey:key];    //所有队列执行完cancel操作后,在所在数组移除
    }
}
objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (!(options & SDWebImageDelayPlaceholder)) {
    dispatch_main_async_safe(^{
        self.image = placeholder;
    });
}
//下载图片,返回一个实现SDWebImageOperation协议的对象。注:该协议只有一个cancel函数
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
    dispatch_main_sync_safe(^{
            completedBlock(image, error, cacheType, url);
        }
    });
}];

//图片下载
- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
                                         options:(SDWebImageOptions)options
                                        progress:(SDWebImageDownloaderProgressBlock)progressBlock
                                       completed:(SDWebImageCompletionWithFinishedBlock)completedBlock {
     ...
     //获取图片
    operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {...}];
    return operation;
}

//queryDiskCacheForkey函数里面首先会先去内存中寻找图片,没有再去本地找,最后才去服务器下载
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
    //获取内存中的图片
    UIImage *image = [self imageFromMemoryCacheForKey:key];
    ...
    //获取本地储存的图片
    UIImage *diskImage = [self diskImageForKey:key];
    ...
    return operation;
}

4.options的作用

typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
    SDWebImageRetryFailed = 1 << 0,
    SDWebImageLowPriority = 1 << 1,
    SDWebImageCacheMemoryOnly = 1 << 2,
    SDWebImageProgressiveDownload = 1 << 3,
    SDWebImageRefreshCached = 1 << 4,
    SDWebImageContinueInBackground = 1 << 5,
    SDWebImageHandleCookies = 1 << 6,
    SDWebImageAllowInvalidSSLCertificates = 1 << 7,
    SDWebImageHighPriority = 1 << 8,
    SDWebImageDelayPlaceholder = 1 << 9,
    SDWebImageTransformAnimatedImage = 1 << 10,
    SDWebImageAvoidAutoSetImage = 1 << 11
};

就说说SDWebImageRetryFailed有什么作用,先看一下注释:

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.

默认options=0,也就是如果不传SDWebImageRetryFailed,图片下载失败了就会被加入黑名单,不会再重新下载,除非设置options=SDWebImageRetryFailed

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];
     }
}

5.其他

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
wself.image = image;
[wself setNeedsLayout];

6.总结

其实SDWebImage的源码很好理解,核心逻辑代码条理清晰,只不过,作者在这基础上完善了很多功能逻辑,功能模块分离,降低耦合度,除了UIImageView控件,还有UIButton控件也能用来设置Image。源码不多,建议感兴趣的都可以去看一下,了解一下。最后,来说一下缓存和本地缓存的区别:1.本地缓存顾名思义是存在本地的,具体是存在应用沙盒的cache文件里,而cache里面会在某些情况下被系统自动清除,比如,内存报警,所以一般放不太重要的,不需要备份的文件。2.缓存是一个大概念,本地缓存也算缓存,这里NSCahce指的应该是内存,看是否已经加在到内存里了,如果已经存在内存,就可以直接从内存中获取设置图片了。

上一篇下一篇

猜你喜欢

热点阅读