Mystery behind reuseIdentifier

Fahad C H
The Startup
Published in
3 min readJul 14, 2020

--

Since the beginning of my iOS app development career, I have been using Table Views and Collection Views like “Geini “ from “Thousand and one night” to grant my wishes without any second thought, and they did everything that asked for as long as I follow the rules(delegation and datasource) of the engagement :).

But recently like every other soul I become discontent and started to question things. The first one obviously about the reuse identifier that Table or Collection views ask from us before granting our wishes.

Do you know why TableView or CollectionView insist on us to give the reuseIdentifier when we ask them to show cells?

I will tell you why these views need this? and then How they are achieving the intended task?

Why

I assume that you already familiar with table or collection view, for instance, TableView, one most important datasource method that you wouldn’t miss would be

inside this method, we would add the code to create and return the expected cell instance which Tableview could use. Suppose you have Datasource which has more than 100k entries(rows) and you want to show it. What would happen if we create a new cell each time and return it? As per my understanding, it would take nearly 1 GB of memory even with the simple data set. So what will happen if we have more dense data? the OS will kick the app out of its misery due to too much memory usage.

Here comes the redeemer reuseIdentifier, from the name it’s self you can guess its usage.

How

The Tableview has an internal queue(hope you know the queue data structure) which is used to store cells for reusing later. So When the cell is scrolled outside the visible area of the Tableview, it is placed within the queue. When we call dequeueReusableCell(withIdentifier:), tableview will try to POP the cell from the queue with that identifier if it exists, if not it will return new cell.

So when a cell gets reused the prepareForReuse() method will get called and you should reset the cell attributes to its normal state. You don’t need to reset the content(labels or images) which would be updated as part of cellForRowAtIndex call.

Hope this clears cell reuse mystery, let me know if I missed anything and open to all type of suggestions.

--

--

Fahad C H
The Startup

iOS developer focused on quality and continuous delivery