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
Using Proxyman to inspect network traffic
Proxyman is a native debugging proxy that can act as a man-in-the-middle between your application and web server. You can use its powerful toolkit to inspect network calls and debug your application on Mac, iOS Simulator, or remote devices effortlessly.
CLICK TO LEARN MORE

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
Using Proxyman to inspect network traffic
Proxyman is a native debugging proxy that can act as a man-in-the-middle between your application and web server. You can use its powerful toolkit to inspect network calls and debug your application on Mac, iOS Simulator, or remote devices effortlessly.
CLICK TO LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

core data

persistence

xcode

swift

ios

iOS developer guide on the main aspects of Core Data

Understand the main concepts of the Core Data framework.

19 Sep 2022 · 5 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy

Impressum