In SwiftData, when does a fetched Task's related Project load, and why can a task list that shows project names do extra store work?
answer
- the fetch returns what you asked for
- first read of the property
- one more query per row
- prefetch named relationships
basics
~20 sA fetch of tasks returns the tasks; each task's project is read from the store the first time code accesses that property. A list that shows task.project?.name per row therefore adds store queries per row unless the fetch prefetches the relationship.
solid answer
~40 sSwiftData loads related models lazily. `context.fetch(FetchDescriptor<ProjectTask>())` or a `@Query` returns task models; their `project` is brought in from the store when code first reads it. A row that shows `task.project?.name` triggers that read for every visible task, and Apple's documentation warns that this can mean an extra fetch per related model and significant overhead. A SQL trace shows the pattern: one query for the tasks, then more queries as each row appears. The fix is to name the relationship in the fetch, `descriptor.relationshipKeyPathsForPrefetching = [\.project]`, so SwiftData obtains the projects in the same fetch, and pass that descriptor to `@Query`. The converse is the benefit: fetching projects does not read their tasks' data until code uses those tasks.
code
swift · 35 linesimport SwiftData
import SwiftUI
@Model
final class Project {
var name: String
@Relationship(inverse: \ProjectTask.project)
var tasks: [ProjectTask] = []
init(name: String) { self.name = name }
}
@Model
final class ProjectTask {
var title: String
var project: Project?
init(title: String) { self.title = title }
}
struct TaskRow: View {
let task: ProjectTask
var body: some View {
VStack(alignment: .leading) {
Text(task.title)
Text(task.project?.name ?? "No project") // first access loads the project
.font(.caption)
}
}
}
func tasksWithProjects(in context: ModelContext) throws -> [ProjectTask] {
var descriptor = FetchDescriptor<ProjectTask>(sortBy: [SortDescriptor(\.title)])
descriptor.relationshipKeyPathsForPrefetching = [\.project]
return try context.fetch(descriptor)
}go deeper
Recall that related models load when you first read the property, not with the fetch.
Explain why a list that shows related data causes extra store reads per row, and which descriptor property prefetches a relationship.
Prove it with a SQL trace before fixing, prefetch only what the screen shows, and re-measure the scroll afterwards.
Set a team habit of tracing the store for list screens in review builds, so per-row reads are found before users feel them.
## Related models are not part of the fetch When SwiftData runs a fetch, through `context.fetch(_:)` or through `@Query` in a view, it returns models of the type you asked for. Their **relationships** are not resolved at that moment. A `ProjectTask` comes back knowing *which* project it belongs to, but the `Project` itself, with its `name`, is read from the store the first time your code accesses `task.project`. This is **lazy loading**, and most of the time it is what you want: - Fetching one project does not read the data of its 5,000 tasks; a task's fields are read when code uses that task. - A detail screen that never shows the project pays nothing for it. Apple's documentation for `relationshipKeyPathsForPrefetching` describes the cost side: fetching employees and showing each one's department means "the model context may need to perform additional fetches for each individual department, resulting in significant overhead". ## The list that does too much work A task list in a project-management app: ```swift List(tasks) { task in TaskRow(task: task) // reads task.project?.name } ``` Every row reads `task.project?.name`. For each task whose project is not loaded yet, SwiftData goes back to the store. With Core Data's SQL debug launch argument, `-com.apple.CoreData.SQLDebug 1`, which also traces SwiftData's default store because that store is built on Core Data, the trace shows one `SELECT` for the tasks and then, as rows are read, queries for each project: in a test on macOS 27, two per row. The screen still works, but scrolling a long list does store work row by row, on the main actor, where `@Query` and the main context run. ## Prefetching the relationship `FetchDescriptor` has a property for exactly this: 1. Build a descriptor for the tasks, with its sort. 2. Set `relationshipKeyPathsForPrefetching = [\.project]`. 3. Use it with `context.fetch(_:)`, or pass it to `@Query` through its `init(_ descriptor:)` form. SwiftData then obtains the related projects as part of the fetch; in the same trace the per-row queries disappear and the projects are read in one batch before the list renders. Writing the descriptor itself, with its other options, is covered with fetching; the relationship lesson here is *when* related models load. | Access pattern | Default behaviour | What to do | |---|---|---| | Rows show a to-one field (`task.project?.name`) | one load per project on first read | prefetch `\.project` | | Detail screen opens one task's project | one load, once | nothing | | Parent fetched, children rarely shown | children's fields not read | nothing; laziness helps | ## The same pattern on the to-many side A project list that shows each project's next task title reads a task's fields on every row. In a SQL trace on macOS 27, the project fetch also read which tasks belong to each project, so counting `project.tasks` cost no further query, but reading a task's `title` issued one more `SELECT` per project as rows were read. For a few projects that is invisible; for hundreds it is the same per-row store work in the other direction, and prefetching `\.tasks`, which in the same trace read every task in one batched query, or showing that detail only on the project screen, removes it. ## Not prefetching everything Prefetching trades queries for memory and up-front time. Prefetch the relationships a screen actually shows, not every relationship on the model; a list that prefetches `\.tasks` on projects, when it only shows project names, loads every task of every project for nothing. ## Diagnosing it - Run with `-com.apple.CoreData.SQLDebug 1` and scroll: a burst of identical `SELECT`s, one per row, is the signature. - Profile scrolling with Instruments and look for time spent in the store while rows appear. - Fix the access pattern first (prefetch, or show less), then measure again. ## Common misunderstandings - A fetched task's `project` is **not** `nil` when not prefetched; reading it loads it. Prefetching changes *when* the project is read, not *whether* you can read it. - `propertiesToFetch` is a different tool: it limits which **attributes** a fetch returns, and reading an attribute that was left out costs another store read. - Prefetching is per fetch: a descriptor that prefetches `\.project` changes nothing for another screen's `@Query` that does not name it.
- Does prefetching change what your code can access?No. Without prefetching, reading `task.project` still works; it just loads the project at that moment. Prefetching moves the work into the original fetch, trading many small reads during rendering for one larger fetch and more memory up front.
- How do you use a prefetching descriptor with @Query in a SwiftUI view?Build a `FetchDescriptor` with its sort, set `relationshipKeyPathsForPrefetching`, and pass it to `@Query`'s `init(_ descriptor:)`. The rows read `task.project?.name` exactly as before; the related projects are already loaded when they do.
- Fetching tasks also loads every related project at the same time.
- A related project is nil until it has been prefetched.
- propertiesToFetch is how you load a relationship with the fetch.
- Prefetch every relationship on the model to be safe.
- A prefetching descriptor on one screen speeds up every other screen's fetch too.