Member-only story
Cache Images in a UICollectionView Using NSCache in Swift 5
Leverage a built-in caching mechanism
Today, we will learn how to use NSCache
in Swift to cache images inside a UICollectionView
.
In short, this is what you will master in this tutorial:
- Understanding what an
NSCache
is and how to use it. - Creating a centered
UICollectionView
layout. - Executing image-loading tasks on a background thread.
- Understanding why it is better to use an
NSCache
instead of a plainDictionary
when we want to cache heavy objects.
This is what we will have at the end of this article:
![](https://miro.medium.com/v2/resize:fit:590/1*ocpchc7cbHu8sUsGq4DHIQ.gif)
The full source code of the project is available at the bottom of the article.
Without further ado, let’s get started.
Let’s Start
First, let’s create a PhotoCollectionViewCell
that simply contains a UIImageView
: