How to cache data in Swift using NSCache
When we develop apps for iOS, we need to perform heavy tasks such as loading images from the network, loading files, etc. It’s a very time-consuming task, which affects the performance of the application. Therefore, we cache or store temporary data for them and reuse them appropriately.
Swift uses NSCache
to store temporary data in memory. It is a mutable collection that uses key-value pairs to store temporary data.
It evicts objects associated with data when the system is low on memory. The data that is evicted from the memory has to be recreated again. We can add, remove, or query items in the cache.
Syntax
The NSCache
class constructor takes two objects: key type and object type.
let cache = NSCache<NSURL, UIImage>()
We can optionally give the cache a name for later use. By default, the value is an empty string.
let cache = NSCache<NSURL, UIImage>()
cache.name = “fetch images”
Storing object
We can set the value to the specified key using the setObject
function, which takes two parameters: the object to store and the key name.
let image = UIImage(named: “kitten.png”)!
cache.setObject(image, forKey: “banner”)