Prefetching in iOS

Jecky Modi
3 min readMay 8, 2022

--

Evert wonder why Social media scroll is so smooth and data are always there when we scroll or it doesn’t take time to load those.

Well, Here I am with a small but a useful feature of prefetching in iOS.

Let’s get started…

We can prefetch data using tableview ad collectionview both but for that we need to register delegate as we are registering dataSource delegate.

tableView.prefetchDataSource = self  ORcollectionView.prefetchDataSource = self

Let’s take an example of tableView.

Now, We already register delegate, we need to use it’s methods by providing UITableViewDataSourcePrefetchingin tableView methods.

There’s two function in the UITableViewDataSourcePrefetching protocol :

protocol UITableViewDataSourcePrefetching {// This is called when the rows are near to the visible area
public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath])

// This is called when the rows move further away from visible area, exa: user scroll in an opposite direction
//
Cancel Unnecessary Fetches
optional public func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath])
}

Let’s take an example of collectionView.

Now, We already register delegate, we need to use it’s methods by providing UICollectionViewDataSourcePrefetching tableView methods.

There’s two function in the UICollectionViewDataSourcePrefetching protocol :

protocol UICollectionViewDataSourcePrefetching {  // This is called when the rows are near to the visible area
public collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath])

// This is called when the rows move further away from visible area, exa: user scroll in an opposite direction
//
Cancel Unnecessary Fetches
optional public collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath])
}

How prefetching works

Here are just observations exactly how many rows outside of visible area will be prefetched.

  1. prefetchRowsAtmethod doesn’t get called for rows which are visible on screen initially without scrolling.
  2. Right after initial visible rows became visible, prefetchRowsAt will be called, and the indexPaths variable contain around 10 rows nearest to the visible area.
  3. Depending on the scrolling speed, the indexPaths in prefetch method will contain different amount of rows. On normal scrolling speed, usually it will contain 1 row. If you scroll at a fast speed, it will contain multiple rows.

When you get used to it, you will find it very useful in multiple places.

That’s it!

Comment if you want an example of prefetching using tableView and collectionView both.

I hope you find it useful. Your clap is giving me encouragement to create these type of stories and also Make sure you follow me on Medium not to miss anything.

Also, let’s connect on Linkedin.

--

--