How it works
FetchRequest is a property wrapper that retrieves Core Data managed objects and keeps them in sync with a view's body. You declare what to fetch — the entity, an optional predicate, and a sort order — and SwiftUI executes the fetch against the environment's managed object context, then re-runs the request and invalidates the view whenever the underlying store changes. Reach for it when a view needs to display persisted Core Data records directly, without manually loading results or wiring up change notifications.
Declare the fetch with the @FetchRequest wrapper
Applying the wrapper to a stored property tells SwiftUI to perform a fetch and bind the live results to that property for the lifetime of the view. Here
@FetchRequestwraps the private propertyitems, so the view always reflects the current contents of the store for that request.Order the results with sortDescriptors
The
sortDescriptors:parameter takes an array ofSortDescriptorvalues that determine the order of the returned objects; pass an empty array for no defined order. The example sorts by thetimestampkey path withorder: .reverse, so the most recent records appear first.Read the live results through FetchedResults
The wrapped value is a
FetchedResultscollection — a random-access view over the fetched managed objects that updates in place as the store changes. The view binds it asitems: FetchedResults<Item>and reads from it like any Swift collection, includingitems.countfor the section header.Drive view content from the fetched objects
Because
FetchedResultsis a collection of identifiable managed objects, it plugs straight into list-building views that iterate and rebuild when results change.ForEach(items)walks eachitem, and the rows read managed-object properties such asitem.namedirectly.
order: .reverse to order: .forward in the sortDescriptors: array and watch the rows in the list reorder from oldest to newest.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct FetchRequestDemo: View {
@FetchRequest(
sortDescriptors: [SortDescriptor(\.timestamp, order: .reverse)]
) private var items: FetchedResults<Item>
var body: some View {
List {
Section("Recent Items (\(items.count))") {
ForEach(items) { item in
Label(item.name, systemImage: "clock")
}
}
}
.padding()
}
}