0

I implement a customized class with NSCache to cache some article

i found a problem, that is while hit the home button on simulator, the cached data seems gone

it will load the data from network but not the cache

if not hit home button, it will fetch data from NSCache

ie. My Cache Code:

#import "ArticleCache.h"

@implementation ArticleCache

static NSCache *Cache;

+ (void)initialize
{
    [super initialize];

    Cache = [[NSCache alloc] init];
    [Cache setCountLimit: 1000];
}

+ (void)cacheResponse:(NSData *)response forURL:(NSURL *)URL
{
    [Cache setObject:response forKey:URL];
}

+ (NSData *)cachedResponseForURL:(NSURL *)URL
{
    return [Cache objectForKey:URL];
}

@end

// don't you guys found that this question just like a poem at least the last char and first char of each line are same.

hlcfan
  • 313
  • 1
  • 2
  • 10

3 Answers3

0

This is the expected behavior of NSCache. It is up to you and your design if you want to let the cache be purged and pull the data again from the server or if you want to save it elsewhere when the app is going to enter the background.

Inertiatic
  • 1,270
  • 1
  • 9
  • 12
  • No problem. This might not be something you want to save with UserDefaults. They are generally used for user settings and preferences. You might find better results saving these urls to a file and saving it to a folder that does not get backed up by iTunes/iCloud. – Inertiatic Mar 13 '14 at 05:18
0

Instead of caching NSData objects, cache NSPurgeableData objects instead. In your + (void)cacheResponse:(NSData *)response forURL:(NSURL *)URL, create a NSPurgeableData object from response and store it.

+ (void)cacheResponse:(NSData *)response forURL:(NSURL *)URL
{
    [Cache setObject:[NSPurgeableData dataWithData:response] forKey:URL];
}
Kedar
  • 1,298
  • 10
  • 20
0

Just to make it more clearer ... Quoted NSCache docs, third paragraph:

NSCache objects differ from other mutable collections in a few ways:

  • The NSCache class incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimizing its memory footprint.
  • You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.
  • Retrieving something from an NSCache object returns an autoreleased result.
  • Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it.

These features are necessary for the NSCache class, as the cache may decide to automatically mutate itself asynchronously behind the scenes if it is called to free up memory.

In other words, you never know when these objects will be removed.

zrzka
  • 20,249
  • 5
  • 47
  • 73