Contents

NSFetchRequest

A description of search criteria used to retrieve data from a persistent store.

Declaration

class NSFetchRequest<ResultType> where ResultType : NSFetchRequestResult

Overview

An instance of NSFetchRequest collects the criteria needed to select and optionally to sort a group of NSManagedObject managed objects held in an NSPersistentStore persistent store. A fetch request contains an NSEntityDescription or an entity name that specifies which entity to search. It frequently also contains:

  • An NSPredicate predicate that specifies which properties to filter by and the constraints on selection, such as, “last name begins with a ‘J’”. If you don’t specify a predicate, then the system fetches all instances of the entity that you specified, subject to other constraints. For more information, see fetch(_:).

  • An array of NSSortDescriptor sort descriptors that specify how to order the returned objects, such as ascending by last name and then by first name.

You can also specify other aspects of a fetch request:

fetchLimit

The maximum number of objects that a request returns

fetchOffset

The number of objects to skip

affectedStores

Which data stores the request accesses

resultType

Whether the fetch returns managed objects, object IDs, dictionaries, or a count

includesPropertyValues and

Whether objects are fully populated with their properties

returnsObjectsAsFaults

Whether the objects are faults

includesSubentities

Whether the fetch includes subentities of the fetched entity

propertiesToFetch

Which properties to fetch

includesPendingChanges

Whether to include unsaved changes

Use execute() to perform the fetch directly on the managed object context that’s associated with the current queue. Or use one of the NSManagedObjectContext methods such as perform(_:) to execute the fetch.

In SwiftUI, you can use a FetchRequest property wrapper to execute the fetch and assign the results to a property. First, create the request:

let request: NSFetchRequest = {
    // Create a fetch request.
    let request = ShoppingItem.fetchRequest()
    
    // Limit the maximum number of items that the request returns.
    request.fetchLimit = 100
            
    // Filter the request results, such as to only return unchecked items.
    request.predicate = NSPredicate(format: "isChecked = false")
    
    // Sort the fetched results, such as ascending by name.
    request.sortDescriptors = [NSSortDescriptor(keyPath: \ShoppingItem.name, ascending: true)]

    return request
}()

Then use a FetchRequest property wrapper with the request to declare a property that receives the objects that the fetch returns:

// Use a `FetchRequest` property wrapper to fetch the managed objects
// and assign the result.
@FetchRequest(fetchRequest: request) private var items: FetchedResults<ShoppingItem>

You often predefine fetch requests in an NSManagedObjectModel managed object model to provide an API to retrieve a stored fetch request by name. Stored fetch requests can include placeholders for variable substitution, and serve as templates for later completion. Fetch request templates allow you to predefine queries with variables to substitute at runtime.

Topics

Managing the Fetch Request’s Entity

Specifying Fetch Constraints

Sorting the Results

Prefetching Related Objects

Managing How Results Are Returned

Grouping and Filtering Dictionary Results

Executing a Fetch Request Directly

Initializers

See Also

Fetch requests