iOS Developer Library

Developer

CoreData Framework Reference NSFetchRequest Class Reference

Options
Deployment Target:

On This Page
Language:

NSFetchRequest

Inheritance


Conforms To


Import Statement


Swift

import CoreData

Objective-C

@import CoreData;

Availability


Available in iOS 3.0 and later.

An instance of NSFetchRequest describes search criteria used to retrieve data from a persistent store.

An instance collects the criteria needed to select and—optionally—order a group of managed objects, or data about records held in a persistent store. A fetch request must contain an entity description (an instance of NSEntityDescription) that specifies which entity to search. It frequently also contains:

  • A predicate (an instance of NSPredicate) that specifies which properties to select by and the constraints on selection, for example “last name begins with a ‘J’”€. If you don’t specify a predicate, then all instances of the specified entity are selected (subject to other constraints, see executeFetchRequest:error: for full details).

  • An array of sort descriptors (instances of NSSortDescriptor) that specify how the returned objects should be ordered, for example by last name then by first name.

You can also specify other aspects of a fetch request—the maximum number of objects that a request should return, and which data stores the request should access. With OS X v10.5 and later you can also specify, for example, whether the fetch returns managed objects or just object IDs, and whether objects are fully populated with their properties (see resultType, includesSubentities, includesPropertyValues, and returnsObjectsAsFaults). With OS X v10.6 and later and on iOS, you can further specify, for example, what properties to fetch, the fetch offset, and whether, when the fetch is executed it matches against currently unsaved changes in the managed object context (see resultType, propertiesToFetch, fetchOffset, and includesPendingChanges). You can also fetch distinct property values, and attribute values that satisfy a given function, as illustrated in Core Data Snippets.

You use NSFetchRequest objects with the method executeFetchRequest:error:, defined by NSManagedObjectContext.

You often predefine fetch requests in a managed object model—NSManagedObjectModel provides API to retrieve a stored fetch request by name. Stored fetch requests can include placeholders for variable substitution, and so serve as templates for later completion. Fetch request templates therefore allow you to pre-define queries with variables that are substituted at runtime.

  • Returns a fetch request configured with a given entity name.

    Declaration

    Objective-C

    + (instancetype)fetchRequestWithEntityName:(NSString *)entityName

    Parameters

    entityName

    The name of the entity to fetch.

    Return Value

    A fetch request configured to fetch using the entity named entityName.

    Discussion

    This method provides a convenient way to configure the entity for a fetch request without having to retrieve an NSEntityDescription object. When the fetch is executed, the request uses the managed object context to find the entity with the given name. The model associated with the context’s persistent store coordinator must contain an entity named entityName.

    Import Statement

    Objective-C

    @import CoreData;

    Availability

    Available in iOS 4.0 and later.

  • Initializes a fetch request configured with a given entity name

    Declaration

    Swift

    convenience init(entityName entityName: String)

    Objective-C

    - (instancetype)initWithEntityName:(NSString *)entityName

    Parameters

    entityName

    The name of the entity to fetch.

    Return Value

    A fetch request configured to fetch using the entity named entityName.

    Discussion

    This method provides a convenient way to configure the entity for a fetch request without having to retrieve an NSEntityDescription object. When the fetch is executed, the request uses the managed object context to find the entity with the given name. The model associated with the context’s persistent store coordinator must contain an entity named entityName.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 4.0 and later.

  • The name of the entity the request is configured to fetch. (read-only)

    Declaration

    Swift

    var entityName: String? { get }

    Objective-C

    @property(nonatomic, readonly, strong) NSString *entityName

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 4.0 and later.

  • entity entity Property

    The entity specified for the receiver.

    Declaration

    Swift

    var entity: NSEntityDescription?

    Objective-C

    @property(nonatomic, strong) NSEntityDescription *entity

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • A Boolean value that indicates whether the receiver includes subentities in the results.

    Declaration

    Swift

    var includesSubentities: Bool

    Objective-C

    @property(nonatomic) BOOL includesSubentities

    Discussion

    YEStrue if the request will include all subentities of the entity for the request, otherwise NOfalse. The default is YEStrue.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • predicate predicate Property

    The predicate of the receiver.

    Declaration

    Swift

    var predicate: NSPredicate?

    Objective-C

    @property(nonatomic, strong) NSPredicate *predicate

    Discussion

    The predicate is used to constrain the selection of objects the receiver is to fetch. For more about predicates, see Predicate Programming Guide.

    If the predicate is empty—for example, if it is an AND predicate whose array of elements contains no predicates—the receiver has its predicate set to nil. For more about predicates, see Predicate Programming Guide.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • The fetch limit of the receiver.

    Declaration

    Swift

    var fetchLimit: Int

    Objective-C

    @property(nonatomic) NSUInteger fetchLimit

    Discussion

    The fetch limit specifies the maximum number of objects that a request should return when executed.

    Special Considerations

    If you set a fetch limit, the framework makes a best effort, but does not guarantee, to improve efficiency. For every object store except the SQL store, a fetch request executed with a fetch limit in effect simply performs an unlimited fetch and throws away the unasked for rows.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

    See Also

    – fetchOffset

  • The fetch offset of the receiver.

    Declaration

    Swift

    var fetchOffset: Int

    Objective-C

    @property(nonatomic) NSUInteger fetchOffset

    Discussion

    The default value is 0.

    This setting allows you to specify an offset at which rows will begin being returned. Effectively, the request will skip over the specified number of matching entries. For example, given a fetch which would normally return a, b, c, d, specifying an offset of 1 will return b, c, d, and an offset of 4 will return an empty array. Offsets are ignored in nested requests such as subqueries.

    This can be used to restrict the working set of data. In combination with fetchLimit, you can create a subrange of an arbitrary result set.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

    See Also

    – fetchLimit

  • The batch size of the receiver.

    Declaration

    Swift

    var fetchBatchSize: Int

    Objective-C

    @property(nonatomic) NSUInteger fetchBatchSize

    Discussion

    The default value is 0. A batch size of 0 is treated as infinite, which disables the batch faulting behavior.

    If you set a non-zero batch size, the collection of objects returned when the fetch is executed is broken into batches. When the fetch is executed, the entire request is evaluated and the identities of all matching objects recorded, but no more than batchSize objects’ data will be fetched from the persistent store at a time. The array returned from executing the request will be a proxy object that transparently faults batches on demand. (In database terms, this is an in-memory cursor.)

    You can use this feature to restrict the working set of data in your application. In combination with fetchLimit, you can create a subrange of an arbitrary result set.

    Special Considerations

    For purposes of thread safety, you should consider the array proxy returned when the fetch is executed as being owned by the managed object context the request is executed against, and treat it as if it were a managed object registered with that context.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

    See Also

    – fetchLimit

  • The persistent stores specified for the receiver.

    Declaration

    Swift

    var affectedStores: [AnyObject]?

    Objective-C

    @property(nonatomic, strong) NSArray *affectedStores

    Discussion

    The contents of the array are the identifiers for the stores to be searched when the fetch request is executed.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • The sort descriptors of the receiver.

    Declaration

    Swift

    var sortDescriptors: [AnyObject]?

    Objective-C

    @property(nonatomic, strong) NSArray *sortDescriptors

    Discussion

    The sort descriptors specify how the objects returned when the fetch request is issued should be ordered—for example by last name then by first name. The sort descriptors are applied in the order in which they appear in the sortDescriptors array (serially in lowest-array-index-first order).

    A value of nil is treated as no sort descriptors.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • The relationship key paths to prefetch along with the entity for the request.

    Declaration

    Swift

    var relationshipKeyPathsForPrefetching: [AnyObject]?

    Objective-C

    @property(nonatomic, copy) NSArray *relationshipKeyPathsForPrefetching

    Discussion

    An array of relationship key-path strings in NSKeyValueCoding notation (as you would normally use with valueForKeyPath:). The default value is an empty array (no prefetching).

    Prefetching allows Core Data to obtain related objects in a single fetch (per entity), rather than incurring subsequent access to the store for each individual record as their faults are tripped. For example, given an Employee entity with a relationship to a Department entity, if you fetch all the employees then for each print out their name and the name of the department to which they belong, it may be that a fault has to be fired for each individual Department object (for more details, see Core Data Performance in Core Data Programming Guide). This can represent a significant overhead. You could avoid this by prefetching the department relationship in the Employee fetch, as illustrated in the following example:

    • NSManagedObjectContext *context = ...;
    • NSEntityDescription *employeeEntity = [NSEntityDescription
    • entityForName:@"Employee" inManagedObjectContext:context];
    • NSFetchRequest *request = [[NSFetchRequest alloc] init];
    • request.tntity = employeeEntity;
    • request.relationshipKeyPathsForPrefetching =
    • [NSArray arrayWithObject:@"department"]];

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • The result type of the receiver.

    Declaration

    Swift

    var resultType: NSFetchRequestResultType

    Objective-C

    @property(nonatomic) NSFetchRequestResultType resultType

    Discussion

    The default value is NSManagedObjectResultType.

    If you set the value to NSManagedObjectIDResultType, this will demote any sort orderings to “best efforts” hints if you do not include the property values in the request.

    Special Considerations

    See also includesPendingChanges for a discussion the interaction of result type with whether pending changes are taken into account.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • A Boolean value that indicates whether, when the fetch is executed it matches against currently unsaved changes in the managed object context.

    Declaration

    Swift

    var includesPendingChanges: Bool

    Objective-C

    @property(nonatomic) BOOL includesPendingChanges

    Return Value

    YEStrue if, when the fetch is executed it will match against currently unsaved changes in the managed object context, otherwise NOfalse.

    Discussion

    YEStrue if, when the fetch is executed it will match against currently unsaved changes in the managed object context, otherwise NOfalse. The default value is YEStrue.

    If the value is NOfalse, the fetch request skips checking unsaved changes and only returns objects that matched the predicate in the persistent store.

    Special Considerations

    A value of YEStrue is not supported in conjunction with the result type NSDictionaryResultType, including calculation of aggregate results (such as max and min). For dictionaries, the array returned from the fetch reflects the current state in the persistent store, and does not take into account any pending changes, insertions, or deletions in the context.

    If you need to take pending changes into account for some simple aggregations like max and min, you can instead use a normal fetch request, sorted on the attribute you want, with a fetch limit of 1.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • An array of property description objects that specify which properties should be returned by the fetch.

    Declaration

    Swift

    var propertiesToFetch: [AnyObject]?

    Objective-C

    @property(nonatomic, copy) NSArray *propertiesToFetch

    Discussion

    Property descriptions are instances of NSPropertyDescription. The property descriptions may represent attributes, to-one relationships, or expressions. The name of an attribute or relationship description must match the name of a description on the fetch request’s entity.

    Special Considerations

    You must set the entity for the fetch request before setting this value, otherwise NSFetchRequest throws an NSInvalidArgumentException exception.

    This value is only used if resultType is set to NSDictionaryResultType.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • A Boolean value that indicates whether the fetch request returns only distinct values for the fields specified by propertiesToFetch.

    Declaration

    Swift

    var returnsDistinctResults: Bool

    Objective-C

    @property(nonatomic) BOOL returnsDistinctResults

    Discussion

    YEStrue if, when the fetch is executed, it returns only distinct values for the fields specified by propertiesToFetch, otherwise NOfalse. The default value is NOfalse.

    Special Considerations

    This value is only used if a value has been set for propertiesToFetch.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • A Boolean value that indicates whether, when the fetch is executed, property data is obtained from the persistent store.

    Declaration

    Swift

    var includesPropertyValues: Bool

    Objective-C

    @property(nonatomic) BOOL includesPropertyValues

    Return Value

    YEStrue if, when the fetch is executed, property data is obtained from the persistent store, otherwise NOfalse.

    Discussion

    YEStrue if, when the fetch is executed, property data is obtained from the persistent store, otherwise NOfalse. The default value is YEStrue.

    You can set includesPropertyValues to NOfalse to reduce memory overhead by avoiding creation of objects to represent the property values. You should typically only do so, however, if you are sure that either you will not need the actual property data or you already have the information in the row cache, otherwise you will incur multiple trips to the database.

    During a normal fetch (includesPropertyValues is YEStrue), Core Data fetches the object ID and property data for the matching records, fills the row cache with the information, and returns managed object as faults (see returnsObjectsAsFaults). These faults are managed objects, but all of their property data still resides in the row cache until the fault is fired. When the fault is fired, Core Data retrieves the data from the row cache—there is no need to go back to the database.

    If includesPropertyValues is NOfalse, then Core Data fetches only the object ID information for the matching records—it does not populate the row cache. Core Data still returns managed objects since it only needs managed object IDs to create faults. However, if you subsequently fire the fault, Core Data looks in the (empty) row cache, doesn't find any data, and then goes back to the store a second time for the data.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • A Boolean value that indicates whether the property values of fetched objects will be updated with the current values in the persistent store.

    Declaration

    Swift

    var shouldRefreshRefetchedObjects: Bool

    Objective-C

    @property(nonatomic) BOOL shouldRefreshRefetchedObjects

    Discussion

    YEStrue if the property values of fetched objects will be updated with the current values in the persistent store, otherwise NOfalse.

    By default, when you fetch objects they maintain their current property values, even if the values in the persistent store have changed. By invoking this method with the parameter YEStrue, when the fetch is executed the property values of fetched objects to be updated with the current values in the persistent store. This provides more convenient way to ensure managed object property values are consistent with the store than by using refreshObject:mergeChanges: (NSManagedObjetContext) for multiple objects in turn.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later.

  • A Boolean value that indicates whether the objects resulting from a fetch using the receiver are faults.

    Declaration

    Swift

    var returnsObjectsAsFaults: Bool

    Objective-C

    @property(nonatomic) BOOL returnsObjectsAsFaults

    Discussion

    YEStrue if the objects resulting from a fetch using the receiver are faults, otherwise NOfalse. The default value is YEStrue. This setting is not used if the result type (see resultType) is NSManagedObjectIDResultType, as object IDs do not have property values. You can set returnsObjectsAsFaults to NOfalse to gain a performance benefit if you know you will need to access the property values from the returned objects.

    By default, when you execute a fetch returnsObjectsAsFaults is YEStrue; Core Data fetches the object data for the matching records, fills the row cache with the information, and returns managed object as faults. These faults are managed objects, but all of their property data resides in the row cache until the fault is fired. When the fault is fired, Core Data retrieves the data from the row cache. Although the overhead for this operation is small, for large datasets it may become non-trivial. If you need to access the property values from the returned objects (for example, if you iterate over all the objects to calculate the average value of a particular attribute), then it is more efficient to set returnsObjectsAsFaults to NOfalse to avoid the additional overhead.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.

  • An array of objects that indicate how data should be grouped before a select statement is run in an SQL database.

    Declaration

    Swift

    var propertiesToGroupBy: [AnyObject]?

    Objective-C

    @property(nonatomic, copy) NSArray *propertiesToGroupBy

    Return Value

    An array of NSPropertyDescription or NSExpressionDescription objects, or key-path strings that indicate how data should be grouped before a select statement is run in an SQL database.

    Discussion

    An array of NSPropertyDescription or NSExpressionDescription objects, or key-path strings that indicate how data should be grouped before a select statement is run in an SQL database.

    If you use this setting, then you must set the resultType to NSDictionaryResultType, and the SELECT values must be literals, aggregates, or columns specified in the GROUP BY. Aggregates will operate on the groups specified in the GROUP BY rather than the whole table. If you set properties to group by, you can also set a having predicate—see havingPredicate.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later.

    See Also

    havingPredicate

  • The predicate used to filter rows being returned by a query containing a GROUP BY.

    Declaration

    Swift

    var havingPredicate: NSPredicate?

    Objective-C

    @property(nonatomic, strong) NSPredicate *havingPredicate

    Discussion

    If a having predicate is supplied, it will be run after the GROUP BY. Specifying a HAVING predicate requires that a GROUP BY also be specified. For a discussion of GROUP BY, see setPropertiesToGroupBy:.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 5.0 and later.

  • These constants specify the possible result types a fetch request can return.

    Declaration

    Swift

    struct NSFetchRequestResultType : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var ManagedObjectResultType: NSFetchRequestResultType { get } static var ManagedObjectIDResultType: NSFetchRequestResultType { get } static var DictionaryResultType: NSFetchRequestResultType { get } static var CountResultType: NSFetchRequestResultType { get } }

    Objective-C

    enum { NSManagedObjectResultType = 0x00, NSManagedObjectIDResultType = 0x01, NSDictionaryResultType = 0x02 NSCountResultType = 0x04 }; typedef NSUInteger NSFetchRequestResultType;

    Constants

    • ManagedObjectResultType

      NSManagedObjectResultType

      Specifies that the request returns managed objects.

      Available in iOS 3.0 and later.

    • ManagedObjectIDResultType

      NSManagedObjectIDResultType

      Specifies that the request returns managed object IDs.

      Available in iOS 3.0 and later.

    • DictionaryResultType

      NSDictionaryResultType

      Specifies that the request returns dictionaries.

      See also includesPendingChanges and propertiesToFetch.

      Available in iOS 3.0 and later.

    • CountResultType

      NSCountResultType

      Specifies that the request returns the count of the objects that match the request.

      Available in iOS 3.0 and later.

    Discussion

    These constants are used by resultType.

    Import Statement

    Objective-C

    @import CoreData;

    Swift

    import CoreData

    Availability

    Available in iOS 3.0 and later.