iOS怎么给图片加缓存

iOS如何给图片加缓存

iOS如何给图片加缓存 


在iOS开发中给从网络获取图片是常有的事情,如果我们加载的图片比较多得话,就应该给图片加上缓存,这样下一次就可以很快的读出图片,提高效率


说明:下面只写了创建一个视图,没有写其他的属性

1.普通的加载图片的方法(没有缓存):

UIImageView * imageView = [[UIImageView alloc]init];
    imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://su.bdimg.com/static/superplus/img/logo_white_ee663702.png"]]];

2.使用第三方库SDWebImage可以给图片添加缓存

下载最新的SDWebImage,直接把他们拖到工程里面即可,把#import "UIImageView+WebCache.h"引入到工程里面,看下面实例就是给图片加了缓存,第一次比较慢,以后就很快了。

[imageView setImageWithURL:[NSURL URLWithString:@"http://su.bdimg.com/static/superplus/img/logo_white_ee663702.png"] placeholderImage:[UIImage imageNamed:@"1.png"]];



placeholderImage:[UIImage imageNamed:@"1.png"],这里是在图片还没有加载出来做的替补图片。