Logo for tanaschita.com

The @FetchRequest property wrapper in SwiftUI

Learn how to request data from the Core Data store in a SwiftUI view

updated on 19 Sep 2022 · 2 min read

A @FetchRequest property wrapper provided by SwiftUI allows us to fetch data from a Core Data store in a SwiftUI view.

A basic fetch request to fetch a list of Item entities looks likes this:

@FetchRequest(
sortDescriptors: [])
private var items: FetchedResults<Item>
Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

The @FetchRequest above is applied to the items property of type FetchedResults<Item>. FetchedResults is a collection type, so we can use it in a List the same way as an array.

List {
ForEach(items) { item in
Text("Item \(item.name ?? "")")
}
}

To filter or sort the results, FetchRequest offers sortDescriptors and predicate as parameters.

@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.date, ascending: true)],
predicate: NSPredicate(format: "name BEGINSWITH %@", "t")
)
private var items: FetchedResults<Item>

The fetch request above will deliver items that start with the letter t and are sorted by their date attribute.

Note: The fetch request and its results use the managed object context stored in the environment. For that reason, we need to inject a Core Data managed object context into the environment before using it. Check out this guide on using Core Data with SwiftUI to learn more.

Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

core data

persistence

swift

ios

Get started with NSPredicate to filter NSFetchRequest in Core Data

Get a quick overview on how to use predicates to filter fetch request results.

20 Mar 2023 · 3 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum