How to Create Core Data Fetch Request with @FetchRequest in SwiftUI

The @FetchRequest property wrapper type makes fetch requests and retrieves the results from a Core Data store. Moreover, the fetch request and its results use the managed object context provided by the environment value managedObjectContext. In this post, you will learn how to use @FetchRequest to fetch data from a Core Data store.

You can read the related posts listed below to help you learn the Core Data store basics.

First of all, start from a new iOS Project with Core Data support, and you will get a pretty new project similar as below.

Project structure

Next, clear and paste the code below to ContentView.swift. And you will learn @FetchRequest from a simplest example.

import SwiftUI
import CoreData

struct ContentView: View {
    @FetchRequest(entity: Item.entity(), sortDescriptors: [])
    private var items: FetchedResults<Item>

    var body: some View {
        List(items) { item in
                Text("Item at \(item.timestamp!, formatter: itemFormatter)")

private let itemFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .medium
    return formatter

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)

In SwiftUI, we use @Environment property wrapper for a variable to attach the shared managed object context to a view.

@Environment(\.managedObjectContext) private var viewContext

Next, we define a variable with the @FetchRequest property wrapper to store the results from a Core Data fetch request.

@FetchRequest(entity: Item.entity(), sortDescriptors: [])
private var items: FetchedResults<Item>

Since SwiftUI, you need not create, execute, and retrieve data from a fetch request manually because the @FetchRequest does all. Back to the code, there are two required parameters in the @FetchRequest property wrapper.

  • entity, it is the kind of modeled object to fetch. In this demo, we use the auto-generated entity called Item.
  • sortDescriptors, it is an array of sort descriptors defines the sort order of the fetched results.

Finally, resume the preview of ContentView.


In addition, you can change the sort order of the fetch request. For example, we sort all items in reverse order by timestamp.

@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],

Leave a Reply

Your email address will not be published. Required fields are marked *