The @FetchRequest property wrapper in SwiftUI
Learn how to request data from the Core Data store in a SwiftUI view
20 Mar 2021 · 2 min read
A @FetchRequest property wrapper provided by SwiftUI makes it easy to fetch data from a Core Data store in a SwiftUI view.
A basic fetch request looks likes this:
@FetchRequest(entity: Item.entity(),sortDescriptors: []) var items: FetchedResults<Item>
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 inText("Item \(item.name ?? "")")}}
To filter or sort the results, FetchRequest offers sortDescriptors and predicate as parameters.
@FetchRequest(entity: Item.entity(),sortDescriptors: [NSSortDescriptor(keyPath: \Item.date, ascending: true)],predicate: NSPredicate(format: "name BEGINSWITH %@", "t")) var items: FetchedResults<Item>
The fetch request above will deliver items that start with the letter t and are sorted by their date attribute.
Related tags
Written by
Articles with related topics