TableView error: "attempt to insert row 1 into section 0, but there are only 0 rows in section 0 after the update"

57 Views Asked by At

enter image description here

func reloadCellOfTableView(_ tableView: UITableView, cell: UITableViewCell) {
    DispatchQueue.main.async {
        if let indexPath = tableView.indexPath(for: cell) {
            tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
        }
    }
}

After I called the above function, the app crashed, and the error log on firebase was:

attempt to insert row 1 into section 0, but there are only 0 rows in section 0 after the update.

This error occurs quite rarely.

I try using tableView.beginUpdates() tableView.endUpdates()

1

There are 1 best solutions below

1
Tayyab Mubeen On

When dealing with UITableViews, it is crucial to maintain a synchronized state between the data source and the table view at all times. If the data source can change in a background thread, be cautious and prioritize synchronization.

To ensure consistency, always call beginUpdate/insert/endUpdate immediately after adding new data to the data source. UITableViews cache changes, which allows for more efficient updates when CPU time and resources are abundant.

Once endUpdates is called, the UITableView queries the data source for the updated number of sections and rows. If the data source is directly linked to the number of sections and rows, ensure that the new counts, including any insertions and deletions, accurately match the data source's numbers.

Finally, a word of caution: Avoid mixing calls to 'reloadData' with beginUpdate/endUpdate pairs. Stick to using either one or the other to ensure smooth updates and prevent potential issues.