NEW: Learn SwiftUI with my free YouTube video series! >>

< How to access a Core Data managed object context from a SwiftUI view   How to filter Core Data fetch requests using a predicate >

How to create a Core Data fetch request using @FetchRequest

Fetch requests allow us to load Core Data results that match specific criteria we specify, and SwiftUI can bind those results directly to user interface elements.

If you followed my Core Data and SwiftUI set up instructions, you’ve already injected your managed object context into the SwiftUI environment.

That step is required. I know, you just want to know how to run a Core Data fetch request and show data inside a SwiftUI list, but if you don’t follow the steps in the link above then using @FetchRequest will crash at runtime because SwiftUI expects that setup to have been done.

Once your managed object context is attached to the environment under the .managedObjectContext key, you can use the @FetchRequest property wrapper to make properties in your views that create and manage Core Data fetch requests automatically.

Creating a fetch request requires two pieces of information: the entity you want to query, and a sort descriptor that determines the order in which results are returned. In my example setup we created a ProgrammingLanguages entity that had name and creator attributes, so we could create a fetch request for it like this:

@FetchRequest(entity: ProgrammingLanguage.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ProgrammingLanguage.name, ascending: true)]) var languages: FetchedResults<ProgrammingLanguage>

That loads all programming languages, sorted alphabetically by their name.

As you can see, the sortDescriptors parameter is an array, so you can provide as many sorting options as you need like this:

@FetchRequest(entity: ProgrammingLanguage.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ProgrammingLanguage.name, ascending: true), NSSortDescriptor(keyPath: \ProgrammingLanguage.creator, ascending: false)]) var languages: FetchedResults<ProgrammingLanguage>

Yes, that’s a massive line of code, so I wouldn’t blame you if you broke it up into something a little easier to read:

@FetchRequest(
    entity: ProgrammingLanguage.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \ProgrammingLanguage.name, ascending: true),
        NSSortDescriptor(keyPath: \ProgrammingLanguage.creator, ascending: false)
    ]
) var languages: FetchedResults<ProgrammingLanguage>

Regardless of how you create your fetch request, the results can be used directly inside SwiftUI views. For example, we could show a table of all languages like this:

List(languages, id: \.self) { language in
    Text(language.name ?? "Unknown"
}

SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!

< How to access a Core Data managed object context from a SwiftUI view   How to filter Core Data fetch requests using a predicate >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 1.0/5

Click here to visit the Hacking with Swift store >>