A few weeks ago I blogged about tactics you can use to reduce memory usage in your iOS app however I came across a neat class that can make your life a lot easier.
NSCache is a very simple class that is little more than an NSMutableDictionary except that it will automatically clear objects when memory usage becomes high or they haven’t been used recently. For an app heavy on file/network IO this is perfect.
Keep Calm’s main view is a grid of images. Usually these are loaded from a thumbnail that is automatically generated in the background every time the user updates their poster. This works fine, however it can take up to 10ms to load a picture, so when scrolling (especially on iPad where up to four pictures are presented in one row) to a new row there is a slight jitter even though the images are loaded asynchronously.
So then I added an NSCache to store all the thumbnails and suddenly scrolling became completely smooth because the thumbnails were only loaded when they needed to be (if it all, one would expect that a tablet with 1GB of RAM could handle ~30 images happily). Another benefit of NSCache is that you can limit the total ‘cost’ of all the items (the cost of an item is a relative number you can dictate).
Obviously it can be used for things other than just images, but if you are working on any kind of app that presents images in a grid you can save yourself a lot of time by using NSCache.