269Caching on Objective-C with NSURLCache

A quick reminder on how caching works in Objective-C.

Initially there is one cache, NSURLCache administrates it.

Get the object:

NSURLCache *cache = [NSURLCache sharedURLCache]

[cache memoryCapacity];
[cache setMemoryCapacity: 1024*1024*1]; // in byte
[cache currentMemoryUsage];

Don't worry about the disk aka the flash memory in iPhone, it's not accessible.

A bit of strange behaviour, either a bug in the software or in my brain: When changing ViewControllers the memoryCapacity seems to reset itself to 0, although previous caches remain intact. Re-setting the memoryCapacity back to the original level seems to solve this. (The cache is not overwritten.)

Using the Cache The whole point of using the cache is to not download online material over again. The following steps make for a happy cache:

//URLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:theURL
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];

The delegate response would allow you to alter the about-to-be-cached-data, leaving it in is not necessary:

- (NSCachedURLResponse *)connection:(NSURLConnection *)c
willCacheResponse:(NSCachedURLResponse *)response {
    NSLog(@"willCacheResponse");
    return response;
}

All in all, not that much to take it. Finding out, that the memoryCapacity gets reset was the most time-consuming bit. For another example, of how to roll your own cache, look at URLCache example.