iOS, Objective-C, Swift, Design and Whatever Comes in Mind
‹ Back to the Blog

Overlooked API of the Day: NSCache

I am almost sure that you have stumbled upon the method didReceiveMemoryWarning. It gets added to every UIViewController that you create usind a template from Xcode.

Image of the default code in didReceiveMemoryWarning

Depending on the memory consumption of your ViewController, it's the systems way of telling you "Hey, please use less memory or I am forced to kill your process". This might be a good time to drop references to cached images that can be re-loaded from disk or via network.

Your app also gets a notification called UIApplicationDidReceiveMemoryWarningNotification when the device will run our of memory. Every object can listen for this notification and act accordingly.

If you do not want do deal with this kind of situation by yourself NSCache assist you. NSCache works like a regular dictionary but will drop elements once the memory pressure gets too high.

You can, for example, put downloaded images into a NSCache. They may get purged during usage of your app. In this case you need to re-download them, which is not great but certainly better than crashing.

You can find the documentation of NSCache over here. And if you need an image cache that writes the cache to disk and manages all of the downloading and storing things for you, please take a look at Kingfisher

"Overlooked API of the Day: NSCache".