Monday, October 9, 2017

Explain: NSCache

What is NSCache?

It's more or less just like a dictionary, with the following additional things (as mentioned by the docs):
The NSCache class incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimising its memory footprint.
You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.
Retrieving something from an NSCache object returns an autoreleased result.
Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it.
You might use it if your application has lots of data that it needs to work with, but you can't keep it all in memory. For example, if you had an app that pulled data from an SQL Lite database or a web service, you might store it in an NSCache after looking it up. Then, when you need it again, you can check the cache first and only need to hit the database if it isn't in the cache. The main advantage in this scenario over using a regular dictionary is that if you put too much stuff in the cache and it starts to fill up memory, it will automatically discard things to free up memory for you.

Objective-c - benefits of using NSCache over a static NSMutableDictionary?

A cache has a number of quirks that make it work well as a cache while being poorly suited to use as a general purpose collection. As noted in the docs:
  • NSCache objects differ from other mutable collections in a few ways:
  • The NSCache class incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimising its memory footprint.
  • You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.
  • Retrieving something from an NSCache object returns an autoreleased result.
  • Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it.
  • These features are necessary for the NSCache class, as the cache may decide to automatically mutate itself asynchronously behind the scenes if it is called to free up memory.