The rules for performBatchUpdates

Kuang Lin
1 min readMar 8, 2021

A better understanding for UICollectionView.performBatchUpdates

Although the latest XCode version (12) is having UICollectionViewDiffableDataSource for better handling of UICollectionView, we usually come across with performBatchUpdates when maintaining the old codes or older apps.

How Does performBatchUpdates works?

Let’s see a sample code,

data.insert("new item", at: 0)
data.remove(at: 2)
collectionView.performBatchUpdates({ collectionView.insertItems(at: [IndexPath(item: 0, section: 0)]) collectionView.deleteItems(at: [IndexPath(item: 2, section: 0)])}, completion: nil)

Here’s how it works,

Step 1. Batch the steps in the block

Step 2. get new item count from dataSource.numberOfItemsInSection.

Step 3. Try to execute the insert/delete commands.(insertItems will trigger cellForItemAt(indexPath), deleteItems simply removes the item.)

Note that:

  1. If we are inserting/deleting on the wrong index, it throws exception,

attempt to insert item 26 into section 0, but there are only 25 items in section 0 after the update

2. In this step, the collectionView has not changed it’s numberOfItemsInSection yet.

Step 4. Check if the item number from collectionView layout is matching with dataSource count.

Note: If the amount is different, the collectionView will simply reload whole data and throw the warning invalid number of items in section

Step 5. Update the CollectionView layout so the collectionView.numberOfItemsInSection will equal to dataSource.numberOfItemsInSection

Other Notes:

  1. Do not delete on same index in one block twice, otherwise it cause unexpected error.
  2. Do not move and delete on same index.

--

--