skip to content

In Core Data, how does NSFetchedResultsController feed a list of sightings grouped by bird family, and what makes it report changes?

level: middleimportance: should knowfreq 65%

answer

  1. a fetch request plus a section key path
  2. the first sort descriptor groups sections
  3. the delegate must implement a change method
  4. a snapshot of NSManagedObjectID items
  5. nothing arrives before processPendingChanges

basics

~20 s

Give NSFetchedResultsController a sorted fetch request, the view context and sectionNameKeyPath family, call performFetch(), then read sections and object(at:). Once its delegate implements a change callback, such as the snapshot method, it tracks that context and reports every change.

solid answer

~50 s

I create the controller with a fetch request, the context the list reads from (the view context for UI), `sectionNameKeyPath: "family"` and usually a nil `cacheName`. The request needs sort descriptors, and the first must order by family so each section is one contiguous run; species second orders the rows. `performFetch()` runs it, and `sections`, `numberOfObjects` and `object(at:)` answer the data source. Change tracking is on only when the delegate implements a change method. Since iOS 13 I implement `controller(_:didChangeContentWith:)`, which delivers a snapshot of section names and `NSManagedObjectID`s for a diffable data source, and once it is implemented no other change callback runs. Changes arrive after the context processes pending changes, so edits and merged saves reach the list. To change the filter I set a new predicate on its `fetchRequest` and call `performFetch()` again, deleting the cache first if one is named.

code

swift · 36 lines
swift
import CoreData
import UIKit

@objc(Sighting)
final class Sighting: NSManagedObject {
    @NSManaged var species: String
    @NSManaged var family: String
}

@MainActor
final class SightingsFeed: NSObject, @preconcurrency NSFetchedResultsControllerDelegate {
    private let dataSource: UITableViewDiffableDataSource<String, NSManagedObjectID>
    private let results: NSFetchedResultsController<Sighting>

    init(viewContext: NSManagedObjectContext,
         dataSource: UITableViewDiffableDataSource<String, NSManagedObjectID>) throws {
        let request = NSFetchRequest<Sighting>(entityName: "Sighting")
        request.sortDescriptors = [
            NSSortDescriptor(keyPath: \Sighting.family, ascending: true),   // must group by the section key
            NSSortDescriptor(keyPath: \Sighting.species, ascending: true)
        ]
        request.fetchBatchSize = 40
        results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: viewContext,
                                             sectionNameKeyPath: #keyPath(Sighting.family), cacheName: nil)
        self.dataSource = dataSource
        super.init()
        results.delegate = self          // not retained by the controller
        try results.performFetch()       // delivers the first snapshot to the delegate
    }

    func controller(_ controller: NSFetchedResultsController<any NSFetchRequestResult>,
                    didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
        let typed = snapshot as NSDiffableDataSourceSnapshot<String, NSManagedObjectID>
        dataSource.apply(typed, animatingDifferences: true)
    }
}

go deeper

for a junior

Recall the four init parameters, that performFetch() must run before reading sections, and that object(at:) and numberOfObjects answer the list's data source.

for a middle

Explain change tracking: a delegate implementing a change method, reports after processPendingChanges, the snapshot callback replacing the per-row ones, and the first sort descriptor grouping the sections.

for a senior

Diagnose the failure modes: rows under wrong headers from a mismatched sort, a frozen list from a delegate with no change method, and stale rows after a reset or a cached predicate change.

for a principal

Weigh it as a standard: one controller per list on the view context, cache names only for fixed queries, and snapshot delivery so every list updates the same reviewed way.

## What the controller is for **`NSFetchedResultsController`** sits between a fetch request and a list. It runs the request, works out **sections** from a key path, answers "how many sections, how many rows, which object is at this index path", and, when it has a delegate, watches its **managed object context** and reports how the result set changed. Its header describes it collecting results without bringing every object into memory at once, faulting objects in batches as rows are accessed. For the bird-watching log, the list groups 30,000 sightings under bird-family headers. ## Setting it up 1. **Build the fetch request.** It must have sort descriptors: creating the controller with none raises `NSInvalidArgumentException` ("An instance of NSFetchedResultsController requires a fetch request with sort descriptors"). 2. **Sort by the section key first.** With `sectionNameKeyPath: "family"`, the first sort descriptor orders by `family`, or by a key with the same relative ordering, such as a persistent attribute behind a transient one. Further descriptors order rows inside a section. 3. **Set `fetchBatchSize`** on the request so rows load in batches. 4. **Create the controller** with `init(fetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:)`, passing the context the list reads from. 5. **Assign the delegate**, then call **`performFetch()`**. 6. **Answer the data source** from `sections`, each section's `name` and `numberOfObjects`, and `object(at:)`. Do not count on an error when step 2 is wrong. Apple's documentation says the fetch fails without a sort descriptor for the section key path, but a request sorted by species alone can come back with rows filed under the wrong family headers. ## The three delegate styles | Callback | Since | What it delivers | |---|---|---| | `controller(_:didChangeContentWith:)` with a snapshot | iOS 13 | section names and `NSManagedObjectID` items, to apply to a diffable data source | | `controller(_:didChangeContentWith:)` with a difference | iOS 13 | a `CollectionDifference<NSManagedObjectID>`, only when `sectionNameKeyPath` is nil | | `controllerWillChangeContent(_:)`, `controller(_:didChange:at:for:newIndexPath:)`, `controller(_:didChange:atSectionIndex:for:)`, `controllerDidChangeContent(_:)` | iOS 3 | per-object and per-section inserts, deletes, moves and updates, sections first | If the snapshot method is implemented, **no other delegate methods are invoked**. The snapshot's items are object IDs, so the cell looks the object up in the view context when it configures itself. How a diffable data source applies a snapshot, and how to refresh cells whose objects changed in place, is covered with table and collection views. ## When changes arrive - **Tracking needs a delegate that implements a change method.** A delegate with no change method, or no delegate at all, means the controller keeps the results as they were when fetched. An empty `controllerDidChangeContent(_:)` is enough to switch tracking on. - **Nothing is reported the instant you set an attribute.** The controller reacts once its context runs `processPendingChanges()`, which the system calls at the end of the current event cycle; code can also call it directly. - **It watches one context.** Objects saved in another context reach the list only after they are merged into this one; how that merge happens is covered in the lesson on managed object contexts. - **Invalidated objects count as deletes**, but a `reset()` of the context, or removing a store, sends no per-object notifications: call `performFetch()` again and reload the list. - **The delegate is not retained.** The header declares it `assign`, so the object that owns the controller should be the delegate. ## Changing the query and the cache The controller's `fetchRequest` is read-only, but the request object itself can be edited when you follow the documented steps: 1. If the controller has a `cacheName`, call `NSFetchedResultsController.deleteCache(withName:)`. 2. Change the predicate or sort descriptors on `fetchRequest`. 3. Call `performFetch()`; the delegate receives the new content. The persistent section cache is checked against the entity, its version hash, the sort descriptors, the section key path and file dates; the header warns that it is not checked against a fetch request or predicate you mutated, which is why a search screen whose predicate changes should pass `nil` for `cacheName`. Give each distinct configuration its own cache name. ## Mistakes worth avoiding - A first sort descriptor that does not group by the section key. - A delegate that implements no change method, then wondering why the list is frozen. - Implementing the snapshot method and the per-row callbacks together. - Changing the predicate under a named cache without deleting it.

  • The family-sectioned list shows Blue Tit under the Ardeidae header; what is wrong with the fetch request?
    Its first sort descriptor does not order by family. The controller expects the request's first sort descriptor to group the results by `sectionNameKeyPath`; sorted by species first, the rows no longer arrive grouped, and they can land under the wrong headers without any error being raised. Make family the first sort descriptor and species the second.
  • You set a new predicate on the controller's fetchRequest for the search box, but the list does not change; why?
    Changing the request does nothing until you call `performFetch()` again; the controller does not watch its own request. With a non-nil `cacheName` you must also call `deleteCache(withName:)` first, because the cache is not checked against a predicate you changed. A search-driven controller is simpler with `cacheName: nil`.
  • After the view context's reset(), the list keeps showing old rows; what does the controller need?
    A `reset()` invalidates every object in the context at once, and the controller sends no per-object deletions for that case. Call `performFetch()` again and reload the list from the controller's new results. Individual invalidated objects, by contrast, are reported to the delegate as deletes.

  • NSFetchedResultsController works without sort descriptors when the section key path is nil.
  • Setting the delegate property alone turns on change tracking.
  • Implement the snapshot callback and the per-row callbacks together for animations.
  • The controller reports a change the instant an attribute is assigned.
  • The controller keeps its delegate alive, so a temporary delegate object is fine.
  • Swapping the predicate on a cached controller is safe without deleting the cache.