资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

SDWebImage的实现原理(UIImageView+WebCach)

创新互联是一家专业提供山城企业网站建设,专注与成都网站设计、做网站HTML5、小程序制作等业务。10年已为山城众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。

        1.作用:

        SDWebImageView的功能很强大,其中UIImageView+WebCach.h的功能主要是下载图片,设置图片缓存.

        2.原理:

        下载图片的原理:通过图片的网站地址URL异步下载图片;

         缓存图片的原理:下载完成的图片会被保存的内存和文件中;加载图片的时候首先会到内存中去找图片,如果没有就到文件中找,再没有才下载图片。

 

        3.用法:

        导入第三方库SDWebImage

        头文件:UIImageView+webCache.h

        主要语句:

[cell.posterImage sd_setImageWithURL:[NSURL URLWithString:album.poster]placeholderImage:[UIImage p_w_picpathNamed:@"s0"]];

        4.例子:使用album中的图片地址字符串,加载图片到UITableViewCell上。

        不用SDWebImageView的方法:

@property(nonatomic,strong)NSMutableDictionary *p_w_picpathMutableDic;

    NSData *readData = self.p_w_picpathMutableDic[album.poster];
    if(readData)
    {
        cell.posterImage.p_w_picpath = [UIImage p_w_picpathWithData:readData];
    }
    else
    {
        NSString *filePath = [self generateFilePath:album.poster];
        NSData *dataFromFile = [NSData dataWithContentsOfFile:filePath];
        if(dataFromFile)
        {
            cell.p_w_picpathView.p_w_picpath = [UIImage p_w_picpathWithData:filePath];
            self.p_w_picpathMutableDic[album.poster] = dataFromFile;
        }
        else
        {
            //异步下载图片,主线程加载,正确
            //手动实现多级缓存(滑动的时候需要重新下载)
            [self downloadImageViewCell:cell withAlbum:album];
            [dataFromFile writeToFile:filePath atomically:YES];
            self.p_w_picpathMutableDic[album.poster] = dataFromFile;
        }
    }
    
//异步下载图片的方法
- (void)downloadImageViewCell:(MXTableViewCell*)cell withAlbum:(MXAlbum *)album
{
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        NSString *p_w_picpathStr = album.poster;
        NSURL *url = [NSURL URLWithString:p_w_picpathStr];
        NSData *p_w_picpathData = [NSData dataWithContentsOfURL:url];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.posterImage.p_w_picpath = [UIImage p_w_picpathWithData:p_w_picpathData];
        });
    });
}

//找文件的路径
- (NSString *)generateFilePath:(NSString *)p_w_picpathURLStr
{
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
    NSString *p_w_picpathName = [p_w_picpathURLStr lastPathComponent];
    return [cachesPath stringByAppendingPathComponent:p_w_picpathName];
}

        采用SDWebImage的方法

        (1)导入三方库SDWebImage

        (2)导入头文件

#import "UIImageView+WebCache.h"

        (3)一句话搞定

[cell.posterImage sd_setImageWithURL:[NSURL URLWithString:album.poster]placeholderImage:[UIImage p_w_picpathNamed:@"s0"]];

本文题目:SDWebImage的实现原理(UIImageView+WebCach)
文章地址:http://cdkjz.cn/article/jepgej.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220