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
Preparing for a technical iOS job interview - updated for iOS 18
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
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
Preparing for a technical iOS job interview - updated for iOS 18
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
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

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

© 2024 tanaschita.com

Privacy policy

Impressum