If your iPhone or iPad app embeds UIWebViews or makes HTTP requests directly with NSURLConnection, it’s important to keep an eye on memory utilization by running it through the profiler occasionally. Web requests can use a lot of memory, and you may find the memory footprint grows and grows the more you use the app. One of the leading causes we see of high memory utilization in an app is failing to explicitly configure the NSURLCache.
Configuring the shared cache
First off, let’s configure the cache when the app starts (before any requests are made) so we can control the amount of memory it utilizes. In your UIApplicationDelegate:
int cacheSizeMemory = 4*1024*1024; // 4MB
int cacheSizeDisk = 32*1024*1024; // 32MB
NSURLCache *sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
The above configures a 4MB in-memory cache with a 32MB disk cache. The disk cache will reside in the default iOS cache directory in a sub-directory called “nsurlcache”.
Responding to memory warnings
The most frequent cause of crashes we’ve seen in apps that use web views is being ejected for not freeing up enough memory when a memory warning comes in. When your app receives a memory warning, you should purge the shared cache to free up memory. Do this in your UIApplicationDelegate:
[[NSURLCache sharedURLCache] removeAllCachedResponses];
Now when you run your app in the profiler, you should see the memory utilization flatten out, and if you trigger a memory warning in the simulator you should see the memory usage drop.
A word of warning
There are a lot of recommendations on StackOverflow about purging the NSURLCache by recreating it, however, we’ve seen this lead to occasional crashes when requests occur on another thread while the cache is being recreated. Our advice is therefore to create the cache once when the app starts and purge it when appropriate.