請你說說SDwebImage這個框架的內(nèi)部實現(xiàn)原理?
當你看到這句話的時候,是不是很熟悉,有可能你在博客上看到一些關(guān)于SDwebImage原理的詳解,也大概記憶了一些標準的答案,但是小編今天要說的網(wǎng)上那些解讀都太膚淺了,如果面試官是個高手,深入問幾句,也許你就熄火了。
首先我們要了解SDwebImage框架為什么出現(xiàn)?
因為在一個App中多圖片下載是一個耗時操作,也是消耗內(nèi)存的操作,如果讓下載過的圖片不重復下載,當面臨這些的問題,該如何解決?
在SDwebImage這個框架還沒有出現(xiàn)之前,一些比較優(yōu)秀的互聯(lián)網(wǎng)公司一些優(yōu)秀App他們是怎么處理這個問題的呢?
@interface ViewController ()
/** tableView的數(shù)據(jù)源 */
@property (nonatomic, strong) NSArray *apps;
@end
@implementation ViewController
pragma mark ----------------------
pragma mark lazy loading
-(NSArray *)apps
{
if (_apps == nil) {
//字典數(shù)組
NSArray *arrayM = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"apps.plist" ofType:nil]];
//字典數(shù)組---->模型數(shù)組
NSMutableArray *arrM = [NSMutableArray array];
for (NSDictionary *dict in arrayM) {
[arrM addObject:[XMGAPP appWithDict:dict]];
}
_apps = arrM;
}
return _apps;
}
pragma mark ----------------------
pragma mark UITableViewDatasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.apps.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"app";
//1.創(chuàng)建cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//2.設置cell的數(shù)據(jù)
//2.1 拿到該行cell對應的數(shù)據(jù)
XMGAPP *appM = self.apps[indexPath.row];
//2.2 設置標題
cell.textLabel.text = appM.name;
//2.3 設置子標題
cell.detailTextLabel.text = appM.download;
//2.4 設置圖標
NSURL *url = [NSURL URLWithString:appM.icon];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
cell.imageView.image = image;
NSLog(@"%zd-----",indexPath.row);
//3.返回cell
return cell;
}
假設我們直接這樣去下載圖片,你可以嘗試寫個小個demo,它會存在兩個問題:
①UI很不流暢
②圖片重復下載
①當UI不流暢,我們應該怎么解決呢?
可以開子線程下載圖片,然后回到主線程刷新UI。
②圖片重復下載,這個又該如何處理?
先把之前已經(jīng)下載過的圖片保存起來,我們可以想到用一個字典講它存儲起來。這個時候又會存在存在一個問題,如果只是單純用一個字典去存儲,當App退出的時候,下次進入還是重新發(fā)起請求,因為你只是將圖片進行內(nèi)存緩存,當App退出的時候,就會釋放掉。這個時候,我們不僅僅要做內(nèi)存緩存,還要做磁盤緩存。
這個時候我們完善后的代碼是這樣的
import "ViewController.h"
import "XMGAPP.h"
@interface ViewController ()
/** tableView的數(shù)據(jù)源 /
@property (nonatomic, strong) NSArray apps;
/ 內(nèi)存緩存 /
@property (nonatomic, strong) NSMutableDictionary images;
/ 隊列 /
@property (nonatomic, strong) NSOperationQueue queue;
/ 操作緩存 */
@property (nonatomic, strong) NSMutableDictionary *operations;
@end
@implementation ViewController
pragma mark ----------------------
pragma mark lazy loading
-(NSOperationQueue *)queue
{
if (_queue == nil) {
_queue = [[NSOperationQueue alloc]init];
//設置最大并發(fā)數(shù)
_queue.maxConcurrentOperationCount = 5;
}
return _queue;
}
-(NSMutableDictionary *)images
{
if (_images == nil) {
_images = [NSMutableDictionary dictionary];
}
return _images;
}
-(NSArray *)apps
{
if (_apps == nil) {
//字典數(shù)組
NSArray *arrayM = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"apps.plist" ofType:nil]];
//字典數(shù)組---->模型數(shù)組
NSMutableArray *arrM = [NSMutableArray array];
for (NSDictionary *dict in arrayM) {
[arrM addObject:[XMGAPP appWithDict:dict]];
}
_apps = arrM;
}
return _apps;
}
-(NSMutableDictionary *)operations
{
if (_operations == nil) {
_operations = [NSMutableDictionary dictionary];
}
return _operations;
}
pragma mark ----------------------
pragma mark UITableViewDatasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.apps.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"app";
//1.創(chuàng)建cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//2.設置cell的數(shù)據(jù)
//2.1 拿到該行cell對應的數(shù)據(jù)
XMGAPP *appM = self.apps[indexPath.row];
//2.2 設置標題
cell.textLabel.text = appM.name;
//2.3 設置子標題
cell.detailTextLabel.text = appM.download;
//2.4 設置圖標
//先去查看內(nèi)存緩存中該圖片時候已經(jīng)存在,如果存在那么久直接拿來用,否則去檢查磁盤緩存
//如果有磁盤緩存,那么保存一份到內(nèi)存,設置圖片,否則就直接下載
//1)沒有下載過
//2)重新打開程序
UIImage *image = [self.images objectForKey:appM.icon];
if (image) {
cell.imageView.image = image;
NSLog(@"%zd處的圖片使用了內(nèi)存緩存中的圖片",indexPath.row) ;
}else
{
//保存圖片到沙盒緩存
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//獲得圖片的名稱,不能包含/
NSString *fileName = [appM.icon lastPathComponent];
//拼接圖片的全路徑
NSString *fullPath = [caches stringByAppendingPathComponent:fileName];
//檢查磁盤緩存
NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
//廢除
imageData = nil;
if (imageData) {
UIImage *image = [UIImage imageWithData:imageData];
cell.imageView.image = image;
NSLog(@"%zd處的圖片使用了磁盤緩存中的圖片",indexPath.row) ;
//把圖片保存到內(nèi)存緩存
[self.images setObject:image forKey:appM.icon];
// NSLog(@"%@",fullPath);
}else
{
//檢查該圖片時候正在下載,如果是那么久什么都捕捉,否則再添加下載任務
NSBlockOperation *download = [self.operations objectForKey:appM.icon];
if (download) {
}else
{
//先清空cell原來的圖片
cell.imageView.image = [UIImage imageNamed:@"Snip20160221_306"];
download = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:appM.icon];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
NSLog(@"%zd--下載---",indexPath.row);
//容錯處理
if (image == nil) {
[self.operations removeObjectForKey:appM.icon];
return ;
}
//演示網(wǎng)速慢的情況
//[NSThread sleepForTimeInterval:3.0];
//把圖片保存到內(nèi)存緩存
[self.images setObject:image forKey:appM.icon];
//NSLog(@"Download---%@",[NSThread currentThread]);
//線程間通信
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//cell.imageView.image = image;
//刷新一行
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
//NSLog(@"UI---%@",[NSThread currentThread]);
}];
//寫數(shù)據(jù)到沙盒
[imageData writeToFile:fullPath atomically:YES];
//移除圖片的下載操作
[self.operations removeObjectForKey:appM.icon];
}];
//添加操作到操作緩存中
[self.operations setObject:download forKey:appM.icon];
//添加操作到隊列中
[self.queue addOperation:download];
}
}
}
//3.返回cell
return cell;
}
-(void)didReceiveMemoryWarning
{
[self.images removeAllObjects];
//取消隊列中所有的操作
[self.queue cancelAllOperations];
}
//1.UI很不流暢 --- > 開子線程下載圖片
//2.圖片重復下載 ---> 先把之前已經(jīng)下載的圖片保存起來(字典)
//內(nèi)存緩存--->磁盤緩存
//3.圖片不會刷新--->刷新某行
//4.圖片重復下載(圖片下載需要時間,當圖片還未完全下載之前,又要重新顯示該圖片)
//5.數(shù)據(jù)錯亂 ---設置占位圖片
/*
Documents:會備份,不允許
Libray
Preferences:偏好設置 保存賬號
caches:緩存文件
tmp:臨時路徑(隨時會被刪除)
*/
這里小編認為有兩個問題比較重要。
①下載這個過程是很重要,一些細心的面試官會問你多圖片下載是怎么實現(xiàn)的?
先判斷放Operation的數(shù)組里,是否存在下載當前的任務,如果存在了就什么都不做,如果沒有再初始化一個Operation任務,然后放到數(shù)組里。并且放到操作隊列中去執(zhí)行下載任務。當圖片下載完了,把該Operation任務從該數(shù)組移除。
②面試官會問你,圖片是如何進行內(nèi)存緩存的?將圖片存在字典里面,它的value是UIImage,但是key是什么呢?
這個key是圖片的url,比如一張圖片的url是http://p16.qhimg.com/dr/48_48_/438ae9d2fbb.png,那么key一定是從這個url字符串去做文章,因為沙盒路徑中/表現(xiàn)文件的層級關(guān)系,所以我們可以截圖url字符串的后部分作為key就可以了。
這個多圖片的實現(xiàn)方式,差不多就是SDwebImage這個框架的前世。
那么SDwebImage的今生已經(jīng)很成熟,大家也用得很多,但是很多人可能只用過它來設置UIImageView,其實SDwebImage不僅可以設置UIImageView,還可以設置UIButton,并且可以播放.gif圖片,或者你想單獨拿到UIIamge也是可以的。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self download];
}
//1.下載圖片且需要獲取下載進度
//內(nèi)存緩存&磁盤緩存
-(void)download
{
[self.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://img4.duitang.com/uploads/blog/201310/18/20131018213446_smUw4.thumb.600_0.jpeg"] placeholderImage:[UIImage imageNamed:@"Snip20160221_306"] options:SDWebImageCacheMemoryOnly | SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
switch (cacheType) {
case SDImageCacheTypeNone:
NSLog(@"直接下載");
break;
case SDImageCacheTypeDisk:
NSLog(@"磁盤緩存");
break;
case SDImageCacheTypeMemory:
NSLog(@"內(nèi)存緩存");
break;
default:
break;
}
}];
NSLog(@"%@",[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]);
}
//2.只需要簡單獲得一張圖片,不設置
//內(nèi)存緩存&磁盤緩存
-(void)download2
{
[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:@"http://img4.duitang.com/uploads/blog/201310/18/20131018213446_smUw4.thumb.600_0.jpeg"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
NSLog(@"%f",1.0 * receivedSize / expectedSize);
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//得到圖片
self.imageView.image = image;
}];
}
//3.不需要任何的緩存處理
//沒有做任何緩存處理|
-(void)download3
{
//data:圖片的二進制數(shù)據(jù)
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:@"http://img4.duitang.com/uploads/blog/201310/18/20131018213446_smUw4.thumb.600_0.jpeg"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
} completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
self.imageView.image = image;
}];
}];
}
//4.播放Gif圖片
-(void)gif
{
NSLog(@"%s",func);
//self.imageView.image = [UIImage imageNamed:@"39e805d5ad6eddc4f80259d23bdbb6fd536633ca"];
UIImage *image = [UIImage sd_animatedGIFNamed:@"麻雀"];
self.imageView.image = image;
}
-(void)type
{
NSData *imageData = [NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/Snip20160221_306.png"];
NSString *typeStr = [NSData sd_contentTypeForImageData:imageData];
NSLog(@"%@",typeStr);
}
SDwebImage中有一個關(guān)于options枚舉,這個枚舉功能很強大,假設后臺給你URL圖片地址,這個時候你將它緩存起來,但是URL的圖片地址已經(jīng)把圖片更換了,這個啟動APP你顯示的還是以前那張圖片,這個你可以設置SDwebImage中options的枚舉值為SDWebImageRefreshCached,它可以刷新本地緩存。這一點很強大。
SDwebImage跟普通多圖片下載不同之處?
①這里SDwebImage跟上面多圖片下載有一點不同的是,SDwebImage中的沙盒緩存圖片的命名方式為對該圖片的URL進行MD5加密,然后得到一個新的字符串設置為key的。
②多圖片下載的時候我們用的NSDictionary字典進行緩存的,但是SDwebImage使用了NSCache類這個類進行緩存,NSCache這個類有一個屬性totalCostLimit可以設置總成本數(shù),如果總成本數(shù)是5 ,如果發(fā)現(xiàn)存的數(shù)據(jù)超過中成本那么會自動回收之前的對象,不需要我們手動移除。自動管理內(nèi)存緩存數(shù)量和內(nèi)存大小。
import "ViewController.h"
@interface ViewController ()<NSCacheDelegate>
/** 注釋 */
@property (nonatomic, strong) NSCache *cache;
@end
@implementation ViewController
-(NSCache *)cache
{
if (_cache == nil) {
_cache = [[NSCache alloc]init];
_cache.totalCostLimit = 5;//總成本數(shù)是5 ,如果發(fā)現(xiàn)存的數(shù)據(jù)超過中成本那么會自動回收之前的對象
_cache.delegate = self;
}
return _cache;
}
//存數(shù)據(jù)
-
(IBAction)addBtnClick:(id)sender
{
//NSCache的Key只是對對象進行Strong引用,不是拷貝(和可變字典的區(qū)別)
for (NSInteger i = 0; i<10; i++) {
NSData *data = [NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/Snip20160221_38.png"];//cost:成本 [self.cache setObject:data forKey:@(i) cost:1]; NSLog(@"存數(shù)據(jù)%zd",i);}
}
//取數(shù)據(jù)
- (IBAction)checkBtnClick:(id)sender
{
NSLog(@"+++++++++++++++");
for (NSInteger i = 0; i<10; i++) {
NSData *data = [self.cache objectForKey:@(i)];
if (data) {
NSLog(@"取出數(shù)據(jù)%zd",i);
}
}
}
//刪除數(shù)據(jù)
- (IBAction)removeBtnClick:(id)sender
{
[self.cache removeAllObjects];
}
pragma mark ----------------------
pragma mark NSCacheDelegate
//即將回收對象的時候調(diào)用該方法
-(void)cache:(NSCache *)cache willEvictObject:(id)obj
{
NSLog(@"回收%zd",[obj length]);
}