skip to content

Table & Collection Views

Data source and delegate patterns, cell reuse via dequeue, and diffable data sources with compositional layout. The perennial question is reuse: why cells recycle and what breaks if one is not reset.

on this pageshow

explore

questions

6

In UIKit, how does a UITableView get its sections and rows from a UITableViewDataSource, and why must cells come from dequeueReusableCell(withIdentifier:for:)?

level: juniorimportance: must knowfreq 80%

answer

  1. the table asks, you answer
  2. two required methods, sections optional
  3. register before you dequeue
  4. a queue of cells that left the screen

basics

~20 s

A UITableView asks its dataSource for section and row counts, then calls tableView(_:cellForRowAt:) only for rows about to appear. dequeueReusableCell(withIdentifier:for:) returns a recycled or new cell of a registered type, so a long list keeps only about a screenful of cells.

solid answer

~40 s

`UITableViewDataSource` has two required methods, `tableView(_:numberOfRowsInSection:)` and `tableView(_:cellForRowAt:)`; `numberOfSections(in:)` is optional and defaults to 1, and `tableView(_:titleForHeaderInSection:)` gives a plain section header. The table view holds its `dataSource` weakly, so the view controller or another object you keep must own it. You register a cell class or nib for a reuse identifier with `register(_:forCellReuseIdentifier:)`, then call `dequeueReusableCell(withIdentifier:for:)` inside `cellForRowAt`: it always returns a cell, either one that scrolled off screen (after calling its `prepareForReuse()`) or a new one built from the registration. Because that cell may have shown another row a moment ago, `cellForRowAt` sets all of its content on every call. When the data changes you tell the table with `reloadData()` or `performBatchUpdates(_:completion:)`, and it asks again.

code

swift · 29 lines
swift
import UIKit

struct Listing { let address: String; let price: String }

final class ListingsViewController: UIViewController, UITableViewDataSource {
    private let tableView = UITableView(frame: .zero, style: .insetGrouped)
    private var sections: [(title: String, listings: [Listing])] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "ListingCell")
        tableView.dataSource = self          // held weakly by the table
        view.addSubview(tableView)
    }

    func numberOfSections(in tableView: UITableView) -> Int { sections.count }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { sections[section].title }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { sections[section].listings.count }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ListingCell", for: indexPath)
        let listing = sections[indexPath.section].listings[indexPath.row]
        var content = cell.defaultContentConfiguration()
        content.text = listing.address
        content.secondaryText = listing.price
        cell.contentConfiguration = content
        return cell
    }
}

go deeper

for a junior

Recall the two required methods, that sections default to one, and the register-then-dequeue pair. Write cellForRowAt from memory, including the content configuration.

for a middle

Explain the reuse queue and why it keeps memory flat, the difference between the two dequeue methods, and how the delegate's responsibilities differ from the data source's.

for a senior

Connect reuse to real bugs: stale content from partial configuration, a data source released because the property is weak, and batch updates whose counts do not match.

for a principal

Be ready to say when an index-path data source is still the right tool on an existing screen and when a team should move new list screens to diffable data sources.

## Two protocols, two jobs A `UITableView` draws nothing on its own. It asks two objects for everything it needs, and both are held **weakly**, so something else (usually the view controller) must keep them alive: - The **data source** (`UITableViewDataSource`) answers *what* is in the table: how many sections, how many rows in each, the cell for each row, optional header and footer titles, and whether rows can be edited or moved. The header describes it as the protocol that "represents the data model object". - The **delegate** (`UITableViewDelegate`) answers *how the table behaves*: what happens on `tableView(_:didSelectRowAt:)`, custom heights, header views, swipe actions and display callbacks such as `tableView(_:willDisplay:forRowAt:)`. Mixing these up is a common junior slip: selection is never a data source method. ## What the data source must answer The protocol's `@required` block holds exactly two methods: 1. `tableView(_:numberOfRowsInSection:)`, the row count for one section. 2. `tableView(_:cellForRowAt:)`, a configured cell for one **index path** (a section number plus a row number). Everything else is optional. `numberOfSections(in:)` defaults to **1** when you leave it out, so a single-section list needs only the two required methods. `tableView(_:titleForHeaderInSection:)` returns a plain string header in a fixed font; a custom header view comes from the delegate instead. Row heights default to `UITableView.automaticDimension`, so cells built with Auto Layout size themselves without a height method. ## Registering and dequeuing **Cell reuse** is the reason a table of ten thousand listings uses about as much memory as a table of twenty. The table keeps a **reuse queue** of cell objects that scrolled out of view, keyed by **reuse identifier**, and hands them back for rows that scroll in. The flow is: 1. In `viewDidLoad`, call `register(_:forCellReuseIdentifier:)` with a cell class (or a nib), or define a prototype cell with that identifier in a storyboard. 2. In `tableView(_:cellForRowAt:)`, call `dequeueReusableCell(withIdentifier:for:)` with the same identifier and the index path you were given. 3. If a cell with that identifier is waiting in the queue, the table calls its `prepareForReuse()` and returns it; otherwise it creates one from the registration, using `init(style:reuseIdentifier:)` for a class. 4. Configure **every** visible field for this row and return the cell. Apple's documentation says to call this method only from `tableView(_:cellForRowAt:)`, because it uses the index path for extra configuration based on the cell's position. Registration must happen before the first call; an unregistered identifier is a programmer error that stops the app with an exception rather than returning `nil`. ## The two dequeue methods | Method | Returns | Use | |---|---|---| | `dequeueReusableCell(withIdentifier:for:)` | always a cell, sized for the row | the normal call inside `cellForRowAt` | | `dequeueReusableCell(withIdentifier:)` | an optional: `nil` when nothing is queued and nothing is registered | older code that creates cells by hand, or a cell needed outside `cellForRowAt` | ## Content configurations Since iOS 14 a cell's text and image are usually set with `defaultContentConfiguration()`: you get a `UIListContentConfiguration`, set `text`, `secondaryText` and `image`, and assign it to `contentConfiguration`. The older `textLabel` and `imageView` properties are marked in the header as to be deprecated in a future release, and they return `nil` once a content configuration is set. Building a fresh configuration on every call also makes the "set everything every time" rule natural. ## Telling the table that data changed The table only knows what the data source last told it. After the model changes: - `reloadData()` asks for all counts and visible cells again, without animation. - `performBatchUpdates(_:completion:)` with `insertRows(at:with:)`, `deleteRows(at:with:)` or `moveRow(at:to:)` animates specific changes; the counts the data source reports afterwards must match the edits, or UIKit raises an exception. - A diffable data source computes those edits for you from a snapshot, which is the newer way to drive the same table. ## Mistakes interviewers listen for - Creating a new `UITableViewCell` in every `cellForRowAt` call instead of dequeuing, which defeats reuse. - Setting a label only in an `if` branch, so a recycled cell keeps the previous row's text. - Creating the data source as a local variable, which the weak `dataSource` property then lets go. - Calling the index-path dequeue method outside `cellForRowAt`, for example to measure a cell.

  • When would you still call dequeueReusableCell(withIdentifier:) without an index path?
    Apple's documentation reserves the index-path version for `tableView(_:cellForRowAt:)` and points to `dequeueReusableCell(withIdentifier:)` when you need a cell at other times. That version returns an optional: `nil` when no cell is queued and nothing is registered, so older code creates one with `init(style:reuseIdentifier:)`. New code registers a class and uses the index-path version.
  • How do the data source and the delegate split a table view's work?
    The data source answers model questions: counts, the cell for each row, header titles, and committing edits or moves. The delegate handles behaviour and appearance: `tableView(_:didSelectRowAt:)`, custom heights and header views, swipe actions and display callbacks. Both properties are weak, so the owner must keep both objects alive.
  • Why prefer defaultContentConfiguration() over setting textLabel?
    Content configurations arrived in iOS 14 and the header marks `textLabel` and `imageView` as to be deprecated, recommending `UIListContentConfiguration`. Those labels also return `nil` once a configuration is set. A configuration is a value you build in full and assign each time, which matches the rule that `cellForRowAt` sets all content.

  • numberOfSections(in:) is required even when the table has one section.
  • dequeueReusableCell gives every row a brand-new cell, so old content cannot leak.
  • The table view retains its data source, so a local data source object is fine.
  • Creating a UITableViewCell with init(style:reuseIdentifier:) in every cellForRowAt call is the normal pattern.
  • Row selection is handled by a UITableViewDataSource method.
open as a page

In UIKit, how do you drive a UICollectionView with UICollectionViewDiffableDataSource and NSDiffableDataSourceSnapshot, and what must the item identifiers be?

level: middleimportance: must knowfreq 70%

basics

~20 s

Create a UICollectionViewDiffableDataSource with a cell provider, build an NSDiffableDataSourceSnapshot of section and item identifiers, and call apply(_:animatingDifferences:); UIKit diffs it against what is shown. Identifiers must be unique, Hashable and stable, ideally each model's ID.

open as a page

In a UIKit listings table, hearts and price-drop badges appear on the wrong homes after a fast scroll; why do reused cells keep that state, and what belongs in prepareForReuse()?

level: seniorimportance: must knowfreq 75%

basics

~20 s

UIKit hands the same cell object to the next row that scrolls in, so any field configure leaves unset keeps the previous row's value. Set every content field in tableView(_:cellForRowAt:) every time; keep prepareForReuse() for non-content resets and clearing handlers.

open as a page

In UIKit, how does UICollectionViewCompositionalLayout build a home screen with a sideways carousel, a two-column grid and a vertical list from items, groups and sections?

level: middleimportance: should knowfreq 40%

basics

~20 s

UICollectionViewCompositionalLayout nests items in groups and groups in sections, each sized with fractional, absolute or estimated dimensions. A section provider returns a different NSCollectionLayoutSection per index: one with orthogonalScrollingBehavior for the carousel, a two-item group for the grid, and a list section.

open as a page

In a UIKit listings collection view using a diffable data source, every live price update makes rows fade out and back in; why, and how should the updates be applied?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Rows are replaced, not updated: the whole listing, price included, is the item identifier, so a new price is a new item, or the code calls reloadItems(:). Key items by stable ID and call reconfigureItems(:) (iOS 15) to update cells in place.

open as a page

As an iOS lead, what list standard do you set for new UIKit screens: collection views with diffable data sources, compositional layout and cell registration, or index-path table views?

level: principalimportance: should knowfreq 35%

basics

~20 s

Default new screens to UICollectionView with compositional layout, CellRegistration and a diffable data source keyed by stable IDs: one model for lists, grids and carousels. Leave working index-path table screens alone and convert one when it is reworked.

open as a page