How to cache data using NSCache?

Caching is a powerful feature for any Application. That makes Application more responsive.
How I leaned to stop worrying about low Memory warning when we are using Caching from Application side.
Yes……..
Apple provides a specialised class called NSCache. That behave similarly to a mutable Dictionary But NSCache have one major difference: iOS Will Automatically remove the data from NSCache if Device is running with low on Memory.
That means we don’t need to worry about size of data and when we are going to store it in NSCache.
NSCache Object are differ from other mutable Collection in some ways : -
- NSCache class incorporates auto-eviction policies. Which insure that NSCache doesn’t use too much memory. Either Device is running low on memory or other application required more memory then iOS Will Automatically start removing the data from NSCached Object that is already taken memory.
2. You can add, remove and query data from NSCache from different thread without having to lock the cache yourself.
3. NSCache doesn’t copy the key objects that are put into it. unlike Mutable Dictionary.
"Talk is cheap. Show me the code."
- Linus TorvaldsLet’s start with NSCache Code …

In above code. We have defined imageCache that cached the image. loadImage first check it into cached if found return else move to load the image and put it into imageCache for later use.
We can add other restriction to NSCache object —
var countLimit: Int
That define how many objects, cache can hold.

var totalCostLimit: Int
You can setup total Cost limit. by default is 0 (Zero) that means there is no limit. if cache cross the total Cost Limit then it will start evicting the object from cache immediately or some time later.

Reference: https://developer.apple.com/documentation/foundation/nscache
Find me on LinkedIn:
