NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

What is the @FetchRequest property wrapper?

Paul Hudson    @twostraws   

Updated for Xcode 14.0 beta 1

SwiftUI gives us a dedicated property wrapper for working with Core Data fetch requests, and it allows us to embed data directly into SwiftUI views without having to write extra logic.

You must provide @FetchRequest with at least one value, which is an array of sort descriptors to arrange the data. You can optionally also provide a predicate to filter the data as needed.

Important: Before using @FetchRequest you must first have injected a Core Data managed object context into the environment – see how to access a Core Data managed object context from a SwiftUI view for instructions on how to do that.

As a basic example, we could show all users from a Core Data context like this:

@FetchRequest(
    sortDescriptors: []
) var users: FetchedResults<User>

That applies no sorting to the data, so the users will be returned in the order they were added. @FetchRequest automatically implies @ObservedObject, so if you use your data in a List, ForEach, or similar, it will automatically be refreshed when the underlying data changes.

Tip: I’ve split the @FetchRequest code across several lines to make it easier to read, but it’s not required.

If you want to sort your data, provide your sort descriptors as an array of key paths, like this:

@FetchRequest(
    sortDescriptors: [
        SortDescriptor(\.name, order: .reverse)
    ]
) var users: FetchedResults<User>

You can provide as many as you want, and they will be evaluated in order.

To add a predicate as well, create an NSPredicate using your format like this:

@FetchRequest(
    sortDescriptors: [
        SortDescriptor(\.name, order: .reverse)
    ],
    predicate: NSPredicate(format: "surname == %@", "Hudson")
) var users: FetchedResults<User>
Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain. The code can be hard to write, full of edge cases, and time-consuming to maintain. RevenueCat provides a backend and wrapper around StoreKit to make things simple so you can focus on building your app.

Explore the docs

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.5/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.