I wish to implement caching feature for an image in iOS. I wish to create a sample app for that, just for my understanding.
Here is what I want to do:
Get a high resolution image from internet and cache it, display it.
Now next time when this ViewController loads up, the image should be loaded from cache and not from internet.
I know how to cache an image using SDWebImage framework. I wish to try it with NSCache.
How can I implement it using NSCache? Examples are welcomed.
EDITED :
- (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;