【发布时间】:2014-04-17 12:26:02
【问题描述】:
我希望在 iOS 中实现图像缓存功能。 我希望为此创建一个示例应用程序,只是为了我的理解。
这是我想做的:
从 Internet 获取高分辨率图像并将其缓存、显示。
现在下次加载这个 ViewController 时,应该从缓存而不是从 Internet 加载图像。
我知道如何使用 SDWebImage 框架缓存图像。我想用 NSCache 试试。
如何使用 NSCache 实现它?欢迎举例。
已编辑:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSCache *cache = [self imageCache];
NSURL *url = [NSURL URLWithString:@"http://i1.ytimg.com/vi/YbT0xy_Jai0/maxresdefault.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:data];
NSString *imagePath = @"http://i1.ytimg.com/vi/YbT0xy_Jai0/maxresdefault.jpg";
// UIImage *image;
if (!(image = [cache objectForKey:imagePath])) { // always goes inside condition
// Cache miss, recreate image
image = [[UIImage alloc] initWithData:data];
if (image) { // Insert image in cache
[cache setObject:image forKey:imagePath]; // cache is always nil
}
}
_imgCache.image = image;
【问题讨论】:
-
这里我放了关于 NSCache 的例子,请访问stackoverflow.com/questions/19326284/…