Member-only story

Cache Images in a UICollectionView Using NSCache in Swift 5

Leverage a built-in caching mechanism

Zafar Ivaev
Better Programming
3 min readSep 10, 2020

Photo by Scott Webb on Unsplash.

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 plain Dictionary when we want to cache heavy objects.

This is what we will have at the end of this article:

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:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Zafar Ivaev
Zafar Ivaev

Written by Zafar Ivaev

Senior iOS Engineer. I write about features of Swift and iOS development practices.

No responses yet

What are your thoughts?