Mallow's Blog

Diffable Datasource in Tableview and Collection view in iOS

UITableView and UICollectionView are the fundamental parts of UIKit. Till iOS 12, we used Datasource to handle tableview and collection views. So, both these UI components have some issues related to UI updates. Example: If we missed to reload the tableview or collection view after updating datasource using local DB, App crashes with the warning message (as shown in the below image) in times.

Above issue was one sample of the UI issues. Similarly, there are some other issues and difficulties occurs in tableview and collection view UIs. For resolving such difficulties, Apple has introduced Diffable datasource in iOS 13 at WWDC19. Diffable datasource has been used in terms of UITableViewDiffableDatasource and UICollectionViewDiffableDataSource. Before iOS 13, We were writing more steps to update UI in tableview and collection views. But, In Diffable datasource we have the direct method to update models without reloading table view or collection view.

What is diffable datasource

A diffable data source is an object, that is a specialized type of data source which works together with your tableview and collection view objects. It provides the behavior you need to manage updates to your table view’s and collection view’s data and UI in a simple, efficient way. It allows to use delegate methods in Tableview and Collection views. It is a replacement of a Datasource of tableView (UITableViewDatasource) and collectionView (UICollectionViewDatasource). This new diffable datasource allows to define a Datasource in terms of snapshot. The snapshot represents the current state of models.  

What is Snapshot

It returns the representation of the current state of data in tableview or collection view. Diffable data sources uses snapshots to provide data for collection views and table views. 

Through a snapshot, you can set up the initial state of the data that displays in a view and later update that data.Table View/Collection View updates (append, insert, delete, move) will be done in the current snapshot of datasource. Following this, the updated snapshot will apply in datasource of tableviews and collection views. It will be automatically updated in UI without any manual reload of tableview or collection views.

How to implement Diffable datasource

1. Create section models and item models to confirm the Hashable type.

2. A Diffable datasource is defined with the tableview object and cell provider. 

3. Create a snapshot and append sections and items models in snapshot. Updated snapshot will be applied into Datasource.

Implement Diffable Datasource in tableview

1.Create a new project in Xcode

2. Add a new view controller in main storyboard

3. Design a view controller with the tableview and create new tableview cell with .nib file name

4. Design a new table view cell with the first name and last name labels. Register TableviewCell to table view with reuse identifier

1. Create section models and item Models

Create below Section model and item models. Hashable will handle the unique items in diffable datasource. So, Duplicated items will not be added in Diffable datasource and UI. Adding to this, Hashable confirmed model needs at least one unique propertyto handle the non-duplicated values. 

In the above image, ContactSection as section model and Contact as item model was used for contact list UI to show in tableview. Section model is defined as Enum cases and item model is confirmed as the Hashable customtype. So, Both will be handled uniquely. In Datasource, we don’t need to use Section model as mandatory to update models in tableview. But, We need Section Model as mandatory in diffable datasource to define and update models in tableview. 

2. A Diffable datasource will define with the table view object and cell provider

Let’s begin by declaring a diffable Datasource before defining a diffable Datasource. Declare a diffable Datasource with selection and item identifiers using above created models.

In the above image, UITableViewDiffableDataSource will use diffable datasource for tableview. ContactSection is a selection identifier and Contact is an Item identifier for this diffable datasource.

Next, we will define and assign diffable datasource into tableview’s datasource using below CreateContactDatasource method. This method need to be called from ViewDidLoad function in swift file.

UITableViewDiffableDatasource will define with a tableview object and cell provider. Cell provider will provide the customised tableview cell to tableview within a closure. This closure have the tableview object, Indexpath and associated Item identifier (Row identifier as Contact). These are the parameters used to handle tableview cell dequeue inside the Cell provider closure. We will dequeue the TableViewCell using the reuse identifier from tableview, customise the TableViewCell’s cell properties and return the cell within a Cell provider closure. Assign a defined diffable datasource to tableview’s datasource. Once we setup this diffable datasource in tableview, it will handle automatically when the items are updated in tableview.

We don’t need to handle cellForRow method when we dequeue the cell for a tableview. It will be handled in diffable datasource definition part itself and also it is a declarative type definition. So, It is easily understandable for beginners also. Don’t need to handle noOfRows method for showing the number of rows to be shown in tableview. Diffable datasource will get the number of rows and sections from the appended items, sections and show in UI.

3. Create a snapshot, append sections and item models into snapshot

In the below add Contact method, We will see about the Snapshot updation and updated snapshot will be added into diffable datasource.

Create a new snapshot as NSDiffableSnapshot with Section and Item model. We need to use ContactSection as section model and Contact as item model in Snapshot too. Both diffable datasource and snapshot model custom types need to be same. By mistake, If we give different models then we will be getting error in code. Snapshot will be created as var type for updating the snapshot. Once an empty snapshot is created, first we need to append sections and the items will be appended into the sections. At least one section has to be added in the snapshot, otherwise we will be experiencing crashes in the app. Updated snapshot will be applied into a diffable datasource using .apply() method. It will be updated in tableview UI automatically. It is not required to reload tableview for every time we update diffable datasource. In the above code, we will append the favourite section as the first section and append the contact list in the favorite section.

Snapshot apply method has Animation and handling completion. So, we can animate the UI updates in tableview while updating the diffable datasource. We can use completion handler to write required code once datasource is updated in tableview. We can call add contact method, where we need to add contact in our code. 

Till now we have seen the basic cell dequeue and initial datasource updation for the tableview. Now, we shall see about updation in already defined and updated datasource. For updating new items into diffable datasource, we can get the current snapshot of the datasource. After that we can add one item, item list, remove one item and remove item list and all possible updation in that snapshot. Once updated in snapshot, apply that snapshot into tableview’s datasource. The updated data source will be updated with animation because we have given animate as “True” in the data source apply method.

Usually, If we need to remove one item from tableview, first we will get index of the model. After that we will remove that item from datasource and reload the tableview. Then only, Item will be removed from the tableview and will be updated in UI also. But, in diffable datasource, we can directly remove the item with only model using deleteItems() method from the current snapshot of datasource. 

Similarly, we can append, delete Items methods, snapshot insert items, move items, delete all items, and other methods for updating the data source. We can handle these all updates in a Diffable data source with the help of Snapshot.

Implement Diffable Datasource in Collection view

Let’s start implementation of diffable datasource in collection view. Add new view controller in a Main Storyboard and add a collection view in that view controller. Create a new Collection view cell with .nib file named as CollectionViewCell. Register collection view cell into collection view with reuse identifier. Customise collection view layout as per our requirement.

1. Create section models and items Models

We can use same ContactSection as section model and Contact as item model for collection view also. Both are Unique custom type models.

2. A Diffable datasource will define with the collection view object and cell provider

Declaration of collection view diffable datasource using UICollectionViewDiffableDatasource object with Section and item models as already used for tableview updates. Both Contactsection and Contact custom model types are unique model types. So, Declaration has been done for collection view datasource.

In collection view, diffable datasource will be defined with collection view object and cell provider as same as tableview. Define a collection view cell provider with collection view object, Indexpath and Item model (Contact as item model) within that closure. While using diffable datasource in collection view, we don’t need to define numberOfItemsInSection and cellForItemAt methods for a collection view. Diffable datasource will handle the dequeue cell and number of items in collection view automatically.

3. Create a snapshot and append sections and items models into snapshot

Create an empty snapshot with section and item models as same in tableview’s snapshot creation and append items into that snapshot. We can call the above add contact method, when we need to contact in collection view and see about the UI updates. Append, remove, move items, insert items and other updates will be handled in collect view easily as same like table view with the help of Snapshot.

Usage of Diffable datasource

1. Simple and direct methods to update UI in tableview and Collection view, more steps are reduced for update UI.

2. We can compare the new datasource and old datasource with the help of snapshot. 

3. We can easily understand, because it was a declarative approach for define and updation.

4. We don’t need to reload tableview and collection views after updating datasource in tableview. It will handle insertion, deletion, reorders automatically in UI.

5. No need to define default methods of Datasource in Diffable DataSource implementation.

Disadvantages of Diffable Datasource

1. We need minimum OS version as iOS 13 for using Diffable datasource in any screen. Because we can’t handle the datasource in version lower to iOS 13.

2. We can’t directly update the values in the particular item. We need to remove that item and replace with the updated item in the same place.

3. We need to add at least one section before adding any one item into tableview or collection view. If you are trying to add item without section, app will be crashed.

Snapshot is the heart of Diffable datasource. Without Snapshot we can’t handle the diffable datasource and it is the easy, efficient way. Diffable datasource approach is reducing the developer’s complexities from the Datasource. We have seen only the basic things of diffable datasource that would be applied in tableview and collection views. For more updates about diffable datasource, we can check Apple Documentation. Completed Diffable datasource Xcode project will be in GitHub

Stay tuned for the next interesting blog..!

Shanmugapriya S,
iOS Team,
Mallow Technologies.

Leave a Reply

%d bloggers like this: