Question

I have a little confusion in understanding the caching mechanism in iOS.

I have been reading this blog on NSURLCache to customize my caching policy. I want my caching to be completely controlled by my server caching headers.

So I set

[request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];

Now the above blog specifies that I can also specify cache policy for NSCachedURLResponse.

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    NSMutableDictionary *mutableUserInfo = [[cachedResponse userInfo] mutableCopy];
    NSMutableData *mutableData = [[cachedResponse data] mutableCopy];
    NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowedInMemoryOnly;

    // ...

    return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
                                                    data:mutableData
                                                userInfo:mutableUserInfo
                                           storagePolicy:storagePolicy];
}

Then whats the use of having a cache policy for the request in first place ? Is storage policy a request parameter or response parameter.

Was it helpful?

Solution

The difference is here:
NSURLRequestCachePolicy is client-server data management feature that describes sources of data that should be loaded (local cache or remote server) and conditions between them.

NSURLCacheStoragePolicy is only client data management feature that describes storage for local cache (memory, local database and etc; only memory; none).

For example if you use NSURLRequestReturnCacheDataElseLoad for request and NSURLCacheStorageAllowedInMemoryOnly for response then such scenario takes place:

  1. You initiate request;
  2. NSURLConnection loads data from server as it first request and there are no any cache;
  3. When response is received it saved to cache storage that based on memory (it will live only while your application is launched;
  4. You initiate the same request on more time;
  5. NSURLConnection loads data from local cache storage;
  6. You close application (cache storage is released), launch it again and initiate the same request;
  7. NSURLConnection loads data from server as cache storage based on memory was released.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top