In Core Data, a 600-student roster stutters while scrolling because each cell shows the student's courses and their teachers; why does every row hit the store, and how do you fix it?
answer
- one query per cell, on the main queue
- relationship faults fire one by one
- the SQL debug launch argument
- returnsObjectsAsFaults does not reach relationships
- key paths, one query per relationship
basics
~20 sEach cell traverses student.courses and course.teacher, and each relationship fault fires its own store query as the row appears. Set relationshipKeyPathsForPrefetching to ["courses", "courses.teacher"] so Core Data loads them per batch in a few queries.
solid answer
~40 sThe fetch returns students, but their `courses` relationships are **relationship faults**. When a cell reads `student.courses`, that fault fires a query for that one student, and reading each course's `teacher` can fire more, all on the main queue while the user scrolls. Running with `-com.apple.CoreData.SQLDebug 1` shows it: the same SELECT repeats with a new bound value for every row. The cure is `relationshipKeyPathsForPrefetching = ["courses", "courses.teacher"]` on the fetch request, which Apple describes as fetching related objects in a single fetch per entity instead of a store trip per record. Combined with `fetchBatchSize`, each batch brings its courses and teachers along. Setting `returnsObjectsAsFaults` to false does not help: it fills the students themselves, not their relationships.
code
swift · 11 linesimport CoreData
func rosterRequest() -> NSFetchRequest<Student> {
let request = NSFetchRequest<Student>(entityName: "Student")
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
request.fetchBatchSize = 40
// Load each batch's courses, and those courses' teachers, in a
// query per relationship instead of a query per row.
request.relationshipKeyPathsForPrefetching = ["courses", "courses.teacher"]
return request
}go deeper
Know that related objects load lazily, so touching a relationship in every cell can make scrolling slow.
Explain relationship faults, set relationshipKeyPathsForPrefetching on a fetch request, and know its default is no prefetching.
Diagnose the storm from the SQL debug log's repeated SELECT, prefetch exactly the paths the cell reads, and explain why returnsObjectsAsFaults and batch size do not fix it.
Ask that list screens are reviewed for per-row relationship access, with the SQL debug log as the evidence, before performance work is signed off.
## What a fault storm is Core Data loads lazily. A fetch for students returns managed objects whose relationships are **faults**: placeholders that resolve the first time you traverse them. That is cheap when you touch a few relationships and expensive when a list touches one per row. A **fault storm** is the second case: every cell that scrolls into view fires one or more relationship faults, and each fault is its own round trip to the persistent store. In the roster, a cell shows the student's name, their course titles and each course's teacher. For each row: 1. Reading `student.name` fills the student from the row cache the fetch already populated. 2. Reading `student.courses` fires the **to-many relationship fault**: one query for this student's courses. 3. Reading each `course.teacher` resolves another relationship, and reading the teacher's `name` may need data that is not cached yet. Multiply by every row that appears, on the `viewContext`, which runs on the main queue, and scrolling stalls. ## Proving it before fixing it Add the launch argument `-com.apple.CoreData.SQLDebug 1` to the scheme's Arguments Passed On Launch. Core Data then logs the SQL statements it sends to an SQLite store, each prefixed with `CoreData: sql:`, in Xcode's console. A fault storm has an unmistakable signature: **the same SELECT, again and again**, each with one bound parameter, one per row. Keep the argument in a debugging scheme, not in anything you ship. ## The fix: relationshipKeyPathsForPrefetching `NSFetchRequest.relationshipKeyPathsForPrefetching` takes an array of **relationship key paths** in key-value coding notation. Apple's documentation says prefetching lets Core Data obtain the related objects in a single fetch per entity, rather than incurring a trip to the store for each record as its faults are tripped. Its default is empty, meaning no prefetching. - `"courses"` loads every fetched student's courses together. - `"courses.teacher"` follows the path one step further and loads those courses' teachers. - Each extra path costs one more query per fetch, or per batch when batching, not one per row. With `fetchBatchSize` set, the fetch first records the matching IDs and then loads students a batch at a time; the prefetch queries run for each batch, so scrolling to a new batch costs a handful of queries instead of dozens. | Approach | Queries for 40 visible rows | Note | |---|---|---| | No prefetching | the batch load, plus one per row for courses, plus teacher lookups | grows with every row | | Prefetch `courses` | the batch load, plus 2 for the course links and courses | teachers still resolve per course | | Prefetch `courses` and `courses.teacher` | the batch load, plus 3 | flat however many rows are visible | Prefetched objects can still report `isFault` as true. Their data is in the row cache, so firing them is an in-memory step with no further SQL, which the debug log confirms. ## What does not fix it - **`returnsObjectsAsFaults = false`** fills each fetched student's attributes up front. Its relationships stay faults, so `student.courses` still fires a query per row. - **A bigger `fetchBatchSize`** changes how many students load at once, not how their relationships resolve. - **Fetching on a background context** does not help the cells: managed objects stay on their own context's queue, so the cells still read objects in the view context and fire their faults there. ## Choosing what to prefetch Prefetching loads everything on the path for every fetched object, so prefetch only what the cell actually shows: - A cell that shows a course count but no titles may be better served by storing a count attribute that your save code maintains, or by a count fetch, than by loading every course. - A path through a large to-many relationship can load far more objects than the screen needs; measure memory as well as time. - The detail screen and the list can use different fetch requests with different prefetch paths. ## Reading the result After the change, the SQL log for a batch shows the batch SELECT, then one SELECT for the course links with the batch's IDs in an IN list, then one for the courses and one for the teachers. Scrolling smoothness should follow; if it does not, the remaining cost is elsewhere, in cell layout or image work, which a profiler will show.
- In Core Data, does prefetching help when the cell only shows how many courses a student takes?It removes the per-row query, but it still loads every course object for every student in the batch. If only a number is shown, a count attribute your code keeps up to date, or a separate count fetch, avoids loading objects you never display. Choose by what the cell reads, then confirm with the SQL debug log and memory use.
- In Core Data, why can a prefetched Course still report isFault as true?Prefetching puts the related rows into the row cache and resolves the relationship, but the Course objects themselves may still be unfilled placeholders. Reading `course.title` then fills the object from the cache without another SQL statement, which is the cost you were trying to remove.
- In Core Data, how do you confirm the fix worked?Run again with `-com.apple.CoreData.SQLDebug 1` and scroll. Instead of one repeated SELECT per row, each batch should show the batch fetch followed by one statement per prefetched relationship, with the batch's IDs in an IN list. Then profile scrolling to confirm the stall is gone.
- Setting returnsObjectsAsFaults to false loads the students' courses too.
- Raising fetchBatchSize fixes relationship faults firing per row.
- Doing the fetch on a background context makes the cells' relationship reads free.
- Prefetching only works for to-one relationships.
- A prefetched object always reports isFault as false.