To get image caching in Swift isn’t too hard. But why do it yourself with NSCache when you can just do it with a framework? A simple Google search for caching on Swift brings you to Kingfisher and Nuke. Which are both frameworks for caching. But I like to use native whenever I can. It helps me understand at a deeper level what is going on, especially when you look into these frameworks. I noticed that what they use is also NSCache. So let’s get started.
I am going to assume in this project that you have some iOS and fundamentals of programming knowledge. You should at least know about UIImage() and what a dictionary or hash is.
This is a Hash.
So for caching, all you need to do is make sure you have imported UIKit. Then make an instance of NSCache. There are two ways you can do it. Up to you. I will do it the way I usually do. If anyone out there reading this thinks that my method isn’t as efficient, please comment and let me know.
let imageCache = NSCache<AnyObject, AnyObject>()
After we create an instance of NSCache we will put the image in cache. So I am going put this under a URLSession which I assume would be the reason why you need to cache. But if you are not using NSCache, you can just do this wherever your image is set. So if you set your UIImage.image at a certain function, just put it there. Not too bad.
So in this code, we are setting a key for the image. This key needs to be unique because if you have two of the same key, well it will confusing for Swift to know which one you want. So URLSession peeps, just use the urlString and you are set. For those that are placing it in a block, you can use the image name. Cool? Cool.
Now that we set the image, we need to be able to retrieve it. This is also pretty simple. It’s just a check to make sure we have the image in cache, if not just load it.
Alrighty then, that is all. You just cached your images using NSCache in Swift 4! Congratulations, you have a more efficient app.
Here is the whole chunk of code:
Definition that should have been up top, but I don’t want to bore you with.
What is NSCache?
According to Apple:
A mutable collection you use to temporarily store transient key-value pairs that are subject to eviction when resources are low.
Pretty much NSCache is just a collection that you use to store objects like a UIImage, NSCache requires the type to be AnyObject so you can store your cache using UIImage() if you incline to do so. iOS/Swift is also smart enough to know when to drop the images if too much memory is being used and it is automatic so no worries there.
A College Student. Software Engineer Intern. Aspiring iOS Developer and Full Stack Engineer.