Don’t reinvent the wheel

16 Oct

Many Cocoa developers haven’t worked a lot with web services. But these days if your working on an iPhone app it’s highly likely you’re touching a network, either to access a full API or maybe just fetch some images to populate a table view. When fetching data from a web service one of the first thoughts early on is (or at least should be) about performance. Caching is a great way to get big performance gains, not only in speed but also in reduced battery consumption and decreased network usage. So, naturally you might think you should some form of cache controller class maybe using NSCache for in memory and perhaps a SQL database for persistent storage. But don’t be to quick to chisel that wheel out of the stone.

Luckily if your using NSURLSession (and you really should be) you’re likely getting this for free and you don’t even realize it. NSURLSession by default uses a shared NSURLCache (each app gets it’s own) to cache responses. This means when you make a request for something like some JSON or an image the response is cached (in memory and / or to disk). So the cache will be used for any requests you make to the same URL later. Well, technically the cache may be used. It depends on the http cache control headers set in the response. So it’s important to understand what cache control headers are set for your end point and how they can affect when / how long your cache is valid for. See HTTP Header Field Definitions for more info on this.

On a final note. You should validate you’re cache. I don’t mean in some kind of checksum sense. I mean just verifying that it’s actually performing as expected. The NSURLCache uses a SQL database that lives in /Library/Caches/. You should take a look at that cache and verify that your intended responses are being cached. Depending on your response sizes and how much data you want to cache you may need to setup a larger cache than the default shared cache.