Search code examples
iosnsdatanscache

confusion in data storage into nscache


i know that im doing a mistake here coz i cant run the project im trying to build and also what im trying to do here is to get a parsed data from an xml then save it into a an nsdata and then put all those data into a cache so when i run my project it doesnt always load for the data.

@implementation ViewController
{    
    NSCache *myCache;    
}


- (void)viewDidLoad
{    
    myCache = [[NSCache alloc] init];
}

//saving data into cache
NSString *imageURL = [currentData.imageLink];
NSURL *url = [NSURL URLWithString:imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
data = [imagesCache objectForKey:@"KEY"];
[imagesCache setObject:imageLinks forKey:@"KEY"];

Solution

  • A few things:

    1. Data downloads should be done on a background thread.
    2. It's best to have your own object in the cache, and that object should download the image and cache both the image and save the image to disk. When the cache gets purged you should remove the image and then reload from disk if required.
    3. This code:

      NSData *data = [NSData dataWithContentsOfURL:url];
      data = [imagesCache objectForKey:@"KEY"];
      [imagesCache setObject:[NSData dataWithContentsOfURL:url] forKey:@"KEY"];
      

    Downloads the date, throws it away and replaces it with whatever was in the cache and then updates the cache with something else. It should be more like:

    [imagesCache setObject:imageLinks forKey:@"KEY"];
    

    For point 2 your objects should confirm to NSDiscardableContent.