Search code examples
iosswiftuitableviewprotocols

Updating all cells on a table view without making the operation too "heavy" for memory


I have a table view with cells, and they can show a checkmark when left swipe action is implemented (the checkmark is just a UIView, which property isHidden gets set to true).

I also have a UIButton on another view controller, and when a user taps it, all checkmarks should be removed. I implement this by using a protocol and a bool computed property on the delegate. The property is called from the protocol.

Here is the method implementation:

extension ItemsTableViewController: UncheckAllCheckedItemsDelegate {
func uncheckAllCheckedItemsButtonDidTapped() {
    if checkedItems.count > 0 {
        checkedItems.removeAll()
        shouldShowCheckmarks = false
    }
}

}

From the property observer of the property (didSet), I call reloadData() on a table view.

Here how it looks like:

var shouldShowCheckmarks: Bool = false {
    didSet {

        tableView.reloadData()
    }
}

I use this property in table view's data source method tableView(_:, cellForRawAt:) like this:

 cell.checkMarkView.isHidden = !shouldShowCheckmarks

It works fine, and all cells get updated (even those, that are not currently visible).

Now, I'm not sure whether it is the best way to update all cells in terms of memory usage. If you know a better way to do this, I would appreciate your help.


Solution

  • All you need to do is to update the check mark for the visible cells. Fortunately, there is a property of UITableView to help you called visibleCells.

    Instead of calling reload data:

    for cell in tableView.visibleCells {
        // update the check mark for this cell
        cell.checkMarkView.isHidden = !shouldShowCheckmarks
    }
    

    As long as you have updated your model data, your non-visible cells will do the right thing the next time they are loaded.