1

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;
z22
  • 10,013
  • 17
  • 70
  • 126
  • here it is i put example about NSCache please visit this http://stackoverflow.com/questions/19326284/what-is-the-proper-way-to-use-nscache-with-dispatch-async-in-a-reusable-table-ce/19326565#19326565 – Nitin Gohel Apr 17 '14 at 12:29

2 Answers2

5

You can add image to cache using and Id:

[imageCache setObject:image forKey:@"myImage"];

Later you can retreive the image by using:

UIImage *image = [imageCache objectForKey:@"myImage"];

Entire flow will be like:

UIImage *image = [imageCache objectForKey:@"myImage"];
if (!image)
{
   // download image
   dispatch_async(dispatch_get_global_queue(0, 0), ^{
       NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:yourURL]];
       if (imageData)
       {
           // Set image to cache
           [imageCache setObject: [UIImage imageWithData:imageData] forKey:@"myImage"];
           dispatch_async(dispatch_get_main_queue(), ^{
               [yourImageView setImage:[UIImage imageWithData:imageData]];
           });
        }
    });
}
else
{
   // Use image from cache
   [yourImageView setImage:image];
}
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
0

Refer the sample code to load image asynchronously and image caching,

https://developer.apple.com/library/ios/samplecode/LazyTableImages/Introduction/Intro.html

Sathish Kumar
  • 219
  • 1
  • 10