Dealing With Duplicated Data and Affected Cell in UITableViewCell
As you know, UITableView really helps developers and designers to display the data simply. The main component of UITableView is the cell (UITableViewCell). All of your data will be displayed in the table through the cells. A set of cells will form a table. You can read full documentation and implementation trough the official documentation on the Apple Developer site.
Personally, In the early days of my exploration with UITableView. I had some issues in using UITableView. I set one cell to “active” condition, but after scrolling down the table I found out that other cells were affected with ✅ emoji and constantly duplicated to other cells below.
As a beginner, I didn’t know why it happened. I tried to ask my mentors at at the Apple Developer Academy, where I used to be enrolled not long ago. Later, we found out that Swift is using “dequeReusableCell” to save its memory use and boost its performance. What do we need to do if we want to display 1000 data? Instead of creating 1000 cells, we just need to create a little visible cell (5–6) and reuse those cells to display another data. That “reuse” thing also caused this to happen. The “active status” was duplicated to another cell after I scrolled down the table. I’ve already found further explanation about “reuse thing” problems. Read this before you continue — > Why we use dequeueReusableCellWithIdentifier and this.
Based on what I’ve read, both of those articles suggest resetting the cell using prepareForReuse(). Just simply change the alpha, isEnabled condition, color, attribute, and the default value of your cell. Wow, it seemed super easy. But wait a minute! Take a look at what Apple recommends us not to do.
Public function to the rescue
After a long journey of digging the internet. I tried to do something with my cell Swift file. I made a simple public function to reset the cell view and call it from my view controller file. This way, we don’t need to reset first and set after. Just call that public function from ViewController.swift file and you can update your cell automatically.
I have already implemented that prepareForReuse() solution and public function solution. So far, I don’t have any issues with my code, but sometimes I get new duplicated image errors when dealing with updating imageView in cell, but I think that’s another case.
Thanks for your attention and wait for another story about “Dealing with imageView in Cell” soon!
Credits and sources: