A simple write-through cache can be a powerful optimization for any system needing fast, frequent access to the same resource (i.e., almost everything ever). It’s especially true for a limited memory environment like iOS, which is also partially bound by processor and bandwidth constraints. Something as common as downloading and displaying an image touches all these pain points, and that makes it a great place to explore the potential of caching, especially if it’s something your app does as often as the Tumblr mobile apps.
Cocoa itself does a fair bit of caching on its own without intervention, but it has many limitations. In the case of downloading an image using NSURLConnection, the entire server response is stored in a shared NSURLCache, but the inner details are infamously murky and entirely dependent on HTTP headers from the server. After you’ve loaded the image into a UIImageView it’s one memory warning away from being lost, or even sooner if it gets slated for recycling from a table cell scrolling off screen.
Today we’re proud to announce the open sourcing of TMCache, which is designed for this and any other situation where there’s a need to persist “expensive” objects and access them rapidly. TMCache is an object cache for iOS and OS X, suitable for any object conforming to the NSCoding protocol (including the basic Foundation data types, collections, and many UIKit objects like UIImage). It consists of two parallel caches, one in memory and one on disk, both coordinated locklessly by GCD. Like NSCache, TMCache will automatically remove objects from memory when the app receives a warning or goes into the background. Unlike NSCache, TMCache can do things like transparently restore objects from disk, access objects asynchronously using blocks, and automatically limit the size of the cache by age or size.
TMCache is available under the Apache 2.0 license on GitHub or as a CocoaPod, including full documentation in HTML and docset format. Let us know if you find it useful!