[iOS][Objective-C]:模拟SDWebImage的底层实现

这是一个简单的demo模拟了SDWebimage框架中底层的实现

效果是点击屏幕将网络图片下载到本地,模拟了社交类软件中点击将图片从网络中下载下来缓存并显示

首先设置一个根节点为数组的plist文件,这边我们暂时存入4个元素,存放网络图片的URL

viewcontroller中懒加载数组数据:
<pre>
-(NSArray *)dataArray{
//判断数组是否为空
if (!_dataArray) {

    _dataArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"PicData2" ofType:@"plist"]];
}
return _dataArray;

}
</pre>

底层实现一个继承NSOperation的自定义类:
首先写一个类方法用于实例化,
这边NSOperation中的mian方法,直接实现Operation中需要做的事情,不需要调用super,
这边的多次点击方法是确保用户多次点击时图片(注意:在已经加载完成的情况下)不会多次加载导致流量损失。
这边的Cancel状态由调用的manager类来设置,之后会提到
<pre>
//
// DownloadIMGOperation.m
// Demo-模拟SDwebImage
//
// Created by admin on 16/8/23.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//

import "DownloadIMGOperation.h"

import "NSString+Path.h"

@interface DownloadIMGOperation ()

@end

@implementation DownloadIMGOperation

+(instancetype)operationWithStringURL:(NSString *)strURL andFinishBlock:(void(^)(UIImage *))finishBlock{

DownloadIMGOperation *op = [[DownloadIMGOperation alloc]init];

op.strURL = strURL;
op.finishBlock = finishBlock;

return op;

}

-(void)main{

NSURL *imgURL = [NSURL URLWithString:self.strURL];

NSData *imgData = [NSData dataWithContentsOfURL:imgURL];

[imgData writeToFile:[self.strURL appendCachePath] atomically:YES];

NSLog(@"图片写入沙盒");

if (self.isCancelled) {
    NSLog(@"多次点击取消图片赋值操作,拦截");
    return;
}

UIImage * image = [UIImage imageWithData:imgData];

[[NSOperationQueue mainQueue]addOperationWithBlock:^{
    
    if (self.finishBlock) {
        self.finishBlock(image);
    }
}];

}

@end
</pre>

在自定义的NSOperation类的基础上建立一个manager类,出来处理具体逻辑:
首先通过方法sharedManager设置一个单例对象,
这里有两个重要的属性:operationCache 和 imageCache
一个用于Operation的缓存,一个用户图片的缓存
下载方法downloadImageWithStrURL主要流程:
1 优先从程序缓存中读取图片,若没有则往下走,有则直接返回
2 从本地沙盒读取图片(如果有的话,有的情况是之前运行过,该图片已经被程序下载到了本地并保存),同时如果从沙盒读取了图片,将图片添加到图片缓存队列,方便下次调用到该图片时,直接从图片缓存队列中读取,比从沙盒的效率更高,若没有则往下走,有则直接返回
3 都没能找到的情况下,从网络下载数据,一旦当Operation开始执行,将它添加在到Operation缓存队列中,用于在之后判断,用户在多次点击后,上一次的Operation没执行完之前,不会多次发起Operation。

Cancel方法: 从Operation缓存列队中取出last,设置它为Cancel,
这边上面提到的cancel状态中,图片赋值返回前做判断截断,保证图片不会多次赋值。
<pre>
//
// DownloadIMGManager.m
// Demo-模拟SDwebImage
//
// Created by admin on 16/8/23.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//

import "DownloadIMGManager.h"

import "DownloadIMGOperation.h"

import "NSString+Path.h"

@interface DownloadIMGManager ()

@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, strong) NSMutableDictionary *imageCache;
@property (nonatomic, strong) NSMutableDictionary *operationCache;

@end

@implementation DownloadIMGManager

+(instancetype)sharedManager{

static id instance;

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    instance = [[DownloadIMGManager alloc]init];
});

return instance;

}

-(NSOperationQueue *)queue{

if (!_queue) {
    _queue = [[NSOperationQueue alloc]init];
}
return _queue;

}

-(NSMutableDictionary *)operationCache{
if (!_operationCache) {
_operationCache = [NSMutableDictionary dictionary];
}
return _operationCache;
}

-(NSMutableDictionary *)imageCache{
if (!_imageCache) {
_imageCache = [NSMutableDictionary dictionary];
}
return _imageCache;
}

-(void)downloadImageWithStrURL:(NSString *)strURL andFinishBlock:(void(^)(UIImage *))finishBlock{

if (self.imageCache[strURL]) {
    
    finishBlock(self.imageCache[strURL]);
    NSLog(@"从缓存读取图片");
    return;
}
else{
    
    UIImage *sandBoxImage = [UIImage imageWithContentsOfFile:[strURL appendCachePath]];
    
    if (sandBoxImage) {
        NSLog(@"从沙盒读取图片");
        finishBlock(sandBoxImage);
        
        [self.imageCache setObject:sandBoxImage forKey:strURL];
        NSLog(@"从沙盒图片放入图片缓存");
        return;
    }
}

DownloadIMGOperation *op = [DownloadIMGOperation operationWithStringURL:strURL andFinishBlock:^(UIImage *image) {
    
    finishBlock(image);
    
    [self.imageCache setObject:image forKey:strURL];
    NSLog(@"图片加入缓存");
    [self.operationCache removeObjectForKey:strURL];
    NSLog(@"操作移出缓存");
}];


[self.queue addOperation:op];
[self.operationCache setObject:op forKey:strURL];

}

-(void)cancelDownloadWithStrURL:(NSString *)strURL{

NSLog(@"进入CANCEL方法");

DownloadIMGOperation *lastOp = self.operationCache[strURL];

[lastOp cancel];

}

@end
</pre>

最后在manager类的基础上添加一个UIImageView的分类方便调用
<pre>
//
// UIImageView+WebCache.m
// Demo-模拟SDwebImage
//
// Created by admin on 16/8/23.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//

import "UIImageView+WebCache.h"

import "DownloadIMGManager.h"

import <objc/runtime.h>

@implementation UIImageView (WebCache)

static char *key = "keyForURL";

-(void)setCurrentStrURL:(NSString *)currentStrURL{

objc_setAssociatedObject(self, key, currentStrURL, OBJC_ASSOCIATION_COPY_NONATOMIC);

}

-(NSString *)currentStrURL{

return objc_getAssociatedObject(self, key);

}

-(void)getWebImageWithStringURL:(NSString *)strURL{

if (![self.currentStrURL isEqualToString:strURL]) {
    
    [[DownloadIMGManager sharedManager] cancelDownloadWithStrURL:self.currentStrURL];
    
}


self.currentStrURL = strURL;

[[DownloadIMGManager sharedManager] downloadImageWithStrURL:strURL andFinishBlock:^(UIImage *image) {
    
    self.image = image;
    
}];

}

@end
</pre>

最后附上demo的链接:
https://github.com/DerrickQin2853/SimulateSDWebImage

感谢阅读

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • SDWebImage[https://github.com/rs/SDWebImage] 分析 Version 4...
    wyanassert阅读 1,961评论 0 8
  • 前不久做了一个生成快照的需求,其中用到 SDWebImage 来下载图片,在使用该框架的过程中也遇到了一些问题,索...
    ShannonChenCHN阅读 14,143评论 12 241
  • SDWebImage是一个开源的第三方库,它提供了UIImageView的一个分类,以支持从远程服务器下载并缓存图...
    devning阅读 439评论 0 0
  • 下载 下载管理器 SDWebImageDownLoader作为一个单例来管理图片的下载操作。图片的下载是放在一个N...
    wind_dy阅读 1,552评论 0 1
  • 本文由 iMetalk 团队的成员 Lefe 完成,主要帮助读者深入理解一个第三方库。 本文不会教你咋么使用SD,...
    Lefe阅读 1,192评论 0 21