Skip to content
DeveloperMemos

How to Use @FetchRequest in SwiftUI

SwiftUI, Fetch Request, Core Data1 min read

@FetchRequest is a property wrapper in SwiftUI that is used to fetch and manage the results of a Core Data fetch request. The property wrapper is applied to a property of a SwiftUI view, and is used to automatically refresh the view whenever the fetch request results change.

Here is an example of how to use @FetchRequest in a SwiftUI view:

1struct ContentView: View {
2 @FetchRequest(
3 entity: Book.entity(),
4 sortDescriptors: [
5 NSSortDescriptor(keyPath: \Book.title, ascending: true)
6 ]
7 ) var books: FetchedResults<Book>
8
9 var body: some View {
10 List(books, id: \.self) { book in
11 Text(book.title)
12 }
13 }
14}

In the example above, the ContentView struct has a property called books that is marked with the @FetchRequest property wrapper. The property wrapper is applied to a property of type FetchedResults<Book>, which is a type provided by Core Data that represents the results of a fetch request.

The @FetchRequest property wrapper is initialized with the following parameters:

entity: The name of the Core Data entity to fetch. In this example, the Book entity is fetched. sortDescriptors: An array of NSSortDescriptor objects that specify how the results should be sorted. In this example, the results are sorted by the title property of the Book entity in ascending order. Once the @FetchRequest property wrapper is applied to a property, the view will automatically refresh whenever the results of the fetch request change. In the example above, the List view is populated with the fetched books, and will automatically update whenever the fetch request results change.

Using the @FetchRequest property wrapper is a convenient way to fetch and manage the results of a Core Data fetch request in a SwiftUI view. It allows the view to automatically refresh whenever the fetch request results change, without the need for manual reloading or observing of the fetch request results.