Search code examples
ioscore-datauicollectionviewnsfetchedresultscontroller

UICollectionView cells hidden after controllerDidChangeContent


I have a UICollectionView whose dataSource is backed by an NSFetchedResultsController.

The cells will sometimes hide after a content change happens. They stay as subviews of the collection view, but isHidden == true. None of my code explicitly hides cells, and a property observer for isHidden is never tripped.

HINT: our code does have a bail-out case where it can modify core data in cellForItem... or willDisplayCell


Solution

  • The problem is that there were times when we'd try to construct the cell being requested, fail, and modify CoreData before returning a fallback version of the cell.

    cellForItem or willDisplayCell are running on the main thread, and we were using performWithBlockAndWait to modify CoreData.

    That was causing a change to the collection view's dataSource on the main thread while the collection view was still updating cells.

    The simple fix was to use performWithBlock instead of performWithBlockAndWait. Now the collection view has a chance to finish updating itself before the data model is changed.

    A better fix would be to make such a failure impossible by the time we get to cellForItem or willDisplayCell.