FetchDescriptor
A type that describes the criteria, sort order, and any additional configuration to use when performing a fetch.
Declaration
struct FetchDescriptor<T> where T : PersistentModelMentioned in
Overview
Use a fetch descriptor to capture the criteria necessary to select, and optionally sort, a specific collection of models from your app’s persistent storage. A fetch descriptor retrieves only a single type of persistent model, and relies on type inference to determine the appropriate type. However, you can configure a fetch descriptor to prefetch related models of different types using the relationshipKeyPathsForPrefetching property.
To fetch a collection of models, first create a fetch descriptor and specify a predicate and one or more sort descriptors. The predicate describes the attributes to filter by and the constraints to apply to those attributes. If you don’t specify a predicate, the fetch returns all models of the inferred type. You can further tweak a fetch by limiting the number of models it returns, or indicating whether the fetch evaluates any unsaved changes when it selects the models to return. After configuring the fetch descriptor, pass it to the model context’s fetch(_:) method to run the fetch.
let descriptor = FetchDescriptor<Recipe>(
predicate: #Predicate { $0.isFavorite == true },
sortBy: [
.init(\.createdAt)
]
)
descriptor.fetchLimit = 10
let favoriteRecipes = try modelContext.fetch(descriptor)If you’re displaying the fetched models in a SwiftUI view, use the descriptor with the Query(_:animation:) macro instead.
struct FavoriteRecipesList: View {
static var fetchDescriptor: FetchDescriptor<Recipe> {
let descriptor = FetchDescriptor<Recipe>(
predicate: #Predicate { $0.isFavorite == true },
sortBy: [
.init(\.createdAt)
]
)
descriptor.fetchLimit = 10
return descriptor
}
@Query(FavoriteRecipesList.fetchDescriptor) private var favoriteRecipes: [Recipe]
var body: some View {
List(favoriteRecipes) { RecipeRowView($0) }
}
}