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()?
answer
- same object, different row
- an if without an else
- non-content resets only
- paths that skip prepareForReuse
basics
~20 sUIKit 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.
solid answer
~50 sA table keeps offscreen cells in a reuse queue and returns the same object from `dequeueReusableCell(withIdentifier:for:)` for a different index path. Code such as `if listing.isFavourite { heartButton.isSelected = true }` with no `else`, or a badge that is shown but never hidden, leaks the last row's state onto the new one. Apple's documentation for `prepareForReuse()` says to reset only attributes not related to content there, such as alpha, editing and selection state, and that `tableView(_:cellForRowAt:)` should always reset all content; an override must call `super`. Clear per-row closures in `prepareForReuse()` too, and add a button's `UIAction` once rather than on every configure: each new action gets an auto-generated identifier, so they pile up and one tap fires for several listings. Do not lean on `prepareForReuse()` for correctness: `reconfigureRows(at:)` updates an existing cell without calling it, and with prefetching a cell can be requested before it is visible.
code
swift · 30 linesimport UIKit
struct Listing { let id: Int; let price: String; let isFavourite: Bool; let isReduced: Bool }
final class ListingCell: UITableViewCell {
let priceLabel = UILabel()
let heartButton = UIButton(type: .system)
let reducedBadge = UILabel()
var onFavouriteTapped: (() -> Void)?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
heartButton.addAction(UIAction { [weak self] _ in self?.onFavouriteTapped?() }, for: .primaryActionTriggered)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func prepareForReuse() {
super.prepareForReuse() // required: the header marks it NS_REQUIRES_SUPER
onFavouriteTapped = nil // drop the previous row's handler
contentView.alpha = 1 // non-content state only
}
// Called from tableView(_:cellForRowAt:) for every row: sets every content field.
func configure(with listing: Listing, onFavourite: @escaping () -> Void) {
priceLabel.text = listing.price
heartButton.isSelected = listing.isFavourite // assigned both ways, never `if ... { = true }`
reducedBadge.isHidden = !listing.isReduced
onFavouriteTapped = onFavourite
}
}go deeper
Recall that dequeued cells are recycled objects, so every field must be set on every call, including turning things off.
Explain the reuse queue, what Apple's documentation says belongs in prepareForReuse(), and why it must call super.
Diagnose stale hearts, stacked actions and late asynchronous writes from a bug report, and name the paths that skip prepareForReuse(), such as reconfigureRows(at:).
Turn the fixes into a review rule for the team: configure sets everything, prepareForReuse stays light, and no correctness depends on it.
## What reuse actually recycles A `UITableView` creates only as many cell objects as it needs to fill the screen plus a few spares. When a row scrolls out of view, its cell goes into a **reuse queue** keyed by its **reuse identifier**; when a new row scrolls in, `dequeueReusableCell(withIdentifier:for:)` hands that **same object** back for a different index path. Every property the cell had is still there: label text, button selection, hidden flags, closures, attached actions. Nothing resets your own subviews' content for you. The hook UIKit calls on the way out of the queue is `prepareForReuse()`, which the header marks `NS_REQUIRES_SUPER`. ## How the bug shows up In the listings app, each row has a price label, a heart button and a "price reduced" badge. The classic sequence: 1. Row 3 is a favourite, so configure sets `heartButton.isSelected = true`. 2. The user flings; row 3's cell leaves the screen and joins the queue. 3. Row 40, not a favourite, dequeues that cell. The configure code only ever sets the heart in an `if listing.isFavourite` branch, so nothing turns it off. 4. Row 40 now shows a filled heart. The same happens to the badge if code shows it for reduced listings but never hides it for the rest. The fix is a rule, not a patch: **every content field is assigned on every configure call, in both directions**. `heartButton.isSelected = listing.isFavourite`, `reducedBadge.isHidden = !listing.isReduced`. ## What goes where | Concern | Where it belongs | Why | |---|---|---| | Text, prices, favourite state, badges | `tableView(_:cellForRowAt:)` or the cell's configure method | Apple's documentation says the delegate in `cellForRowAt` should always reset all content | | Alpha, editing and selection state | `prepareForReuse()` | the documentation lists these non-content attributes as what to reset there | | A per-row tap closure | cleared in `prepareForReuse()`, set again in configure | a stale closure would act on the previous listing | | Adding the button's action | once, in the cell's initializer | adding a new `UIAction` on every configure stacks handlers | The documentation frames the content rule as a performance point: resetting content in `prepareForReuse()` only to overwrite it in `cellForRowAt` doubles work on the scroll path. ## Per-row actions and late callbacks Two reuse bugs do not involve labels at all: - **Stacked actions.** `addAction(_:for:)` uniques actions by identifier, and a `UIAction` created without one gets an auto-generated identifier. If configure adds a fresh `UIAction` each time, a cell reused five times carries five closures, each capturing a different listing, and one tap toggles them all. (Calling `addTarget(_:action:for:)` again with the same target and action is documented as safe, so the selector style does not pile up that way.) Add the action once in `init(style:reuseIdentifier:)` and route it through a closure property that configure replaces and `prepareForReuse()` sets to `nil`, or give the action a fixed identifier so each add replaces the last. - **Work that finishes after reuse.** Anything asynchronous a cell starts for its row (a lookup, a formatter, a load) can complete after the cell already shows another row. Record which listing ID the cell is configured for, compare it when the work completes, and cancel the work in `prepareForReuse()`. How an image pipeline handles this is the subject of the lesson on image loading. ## Paths that skip prepareForReuse() Treat `prepareForReuse()` as a tidy-up hook, never as the place correctness lives, because several paths bypass it: - `reconfigureRows(at:)` (iOS 15) and a snapshot's `reconfigureItems(_:)` update an **existing** cell; the documentation says the table view does not call `prepareForReuse()` in that case. - A cell without a reuse identifier never gets the call either, as the same documentation notes. - With `isPrefetchingEnabled` (true by default), a cell for a row can be requested **before** it is on screen. For collection views, Apple's documentation suggests updating visual state such as selection in `collectionView(_:willDisplay:forItemAt:)` for that reason. Separately, a `prefetchDataSource` receives `tableView(_:prefetchRowsAt:)` to start loading data early and `tableView(_:cancelPrefetchingForRowsAt:)` to cancel it. ## Review checklist - Does configure assign every visible field, including the "off" case? - Does `prepareForReuse()` call `super` and touch only non-content state and handlers? - Are actions added once, not per configure? - Does any asynchronous completion check that the cell still shows the same listing? - Would the screen still be correct if `prepareForReuse()` were never called? Giving every row its own reuse identifier hides the symptom by disabling reuse, and memory then grows with the list; it is not a fix.
- Why does Apple advise against resetting content in prepareForReuse()?The documentation frames it as avoiding performance issues: `cellForRowAt` must set all content anyway, so clearing it first is wasted work on the scroll path. It is also unsafe as the only reset, because `reconfigureRows(at:)` and `reconfigureItems(_:)` update a cell without calling `prepareForReuse()`.
- A cell starts an asynchronous lookup for its listing and writes the result when it finishes; what breaks, and what is the guard?After a fast scroll the cell may already show another listing, so the late result paints the wrong row. Store the listing ID the cell is configured for, compare it when the work completes, and cancel outstanding work in `prepareForReuse()`. The image-loading specifics are covered with the image pipeline.
- What changes for cell configuration when prefetching is enabled?`isPrefetchingEnabled` is true by default, so the data source can be asked for a cell before it is visible. Configuration must not assume visibility; for collection views Apple suggests applying visual state such as selection in `collectionView(_:willDisplay:forItemAt:)`. A `prefetchDataSource` is separate and only warns you to start or cancel data work.
A reused cell is a hotel room between guests. Housekeeping tidies the room and resets the lights (prepareForReuse), but the front desk must write the new guest's name and bill on every check-in (cellForRowAt). A desk that writes a name only for members leaves the last member's name on the door for the next guest.
- prepareForReuse() is where the new row's text and favourite state should be set.
- UIKit clears a reused cell's labels and button states before returning it.
- Overriding prepareForReuse() without calling super is harmless.
- Giving each row a unique reuse identifier is the proper fix for stale cells.
- Every update path calls prepareForReuse(), so it is a reliable place to reset content.