NEW: Join my free 100 Days of SwiftUI challenge today! >>

What is the @FetchRequest property wrapper?

Paul Hudson    @twostraws   

Fully updated for Xcode 11 GM

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 two values: the entity you want to read, and any 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(
    entity: User.entity(),
    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 @ObservableObject, 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 keypaths, like this:

@FetchRequest(
    entity: User.entity(), 
    sortDescriptors: [
        NSSortDescriptor(keyPath: \User.name, ascending: false)
    ]
) 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(
    entity: User.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \User.name, ascending: false),
    ],
    predicate: NSPredicate(format: "surname == %@", "Hudson")
) var users: FetchedResults<User>

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Similar solutions…

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 us know!