A collection view displays an ordered collection of cells in customizable layouts. The UICollectionViewDataSourcePrefetching protocol helps provide a smoother user experience by prefetching the data necessary for upcoming collection view cells. When you enable prefetching, the collection view requests the data before it needs to display the cell. When it’s time to display the cell, the data is already locally cached.
The image below shows cells outside the bounds of the collection view that have been prefetched.
The root view controller uses an instance of the CustomDataSource class to provide data to its UICollectionView instance. The CustomDataSource class implements the UICollectionViewDataSourcePrefetching protocol to begin fetching the data required to populate cells.
In addition to assigning the CustomDataSource instance to the collection view’s dataSource property, you must also assign it to the prefetchDataSource property.
Load Data Asynchronously
You use data prefetching when loading data is a slow or expensive process—for example, when fetching data over the network. In these circumstances, perform data loading asynchronously. In this sample, the AsyncFetcher class is used to fetch data asynchronously, simulating a network request.
When prefetching is complete, the cell’s data is added to the AsyncFetcher‘s cache, so it’s ready to be used when the cell is displayed. The cell’s background color changes from white to red when data is available for that cell.
Populate Cells for Display
Before populating a cell, the CustomDataSource first checks for any prefetched data that it can use. If none is available, the CustomDataSource makes a fetch request and the cell is updated in the fetch request’s completion handler.