Documentation Archive

Developer

Core Data Programming Guide

On This Page

Fetching Objects

Now that data is stored in the Core Data persistent store, you will use an NSFetchRequest to access that existing data. The fetching of objects from Core Data is one of the most powerful features of this framework.

Fetching NSManagedObject Instances

In this example you start by constructing an NSFetchRequest that describes the data you want returned. This example does not add any requirements to that data other than the type of entity being returned. You then call executeFetchRequest:error: on the NSManagedObjectContext and pass in the request along with a pointer to an error.

Objective-C

  1. NSManagedObjectContext *moc = ;
  2. NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
  3. NSError *error = nil;
  4. NSArray *results = [moc executeFetchRequest:request error:&error];
  5. if (!results) {
  6. NSLog(@"Error fetching Employee objects: %@\n%@", [error localizedDescription], [error userInfo]);
  7. abort();
  8. }

Swift

  1. let moc = …
  2. let employeesFetch = NSFetchRequest(entityName: "Employee")
  3. do {
  4. let fetchedEmployees = try moc.executeFetchRequest(employeesFetch) as! [EmployeeMO]
  5. } catch {
  6. fatalError("Failed to fetch employees: \(error)")
  7. }

The executeFetchRequest:error: method has two possible results. It either returns an NSArray object with zero or more objects, or it returns nil. If nil is returned, you have received an error from Core Data and need to respond to it. If the array exists, you receive possible results for the request even though the NSArray may be empty. An empty NSArray indicates that there were no records found.

Filtering Results

The real flexibility in fetching objects comes in the complexity of the fetch request. To begin with, you can add an NSPredicate object to the fetch request to narrow the number of objects being returned. For example, if you only want Employee objects that have a firstName of Trevor, you add the predicate directly to NSFetchRequest:

Objective-C

  1. NSString *firstName = @"Trevor";
  2. [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"firstName == %@", firstName]];

Swift

  1. let firstName = "Trevor"
  2. fetchRequest.predicate = NSPredicate(format: "firstName == %@", firstName)

In addition to narrowing the objects being returned, you can configure how those objects are returned. For example, you can instruct Core Data to return NSDictionary instances instead of fully formed NSManagedObject instances. Further, you can configure the NSFetchRequest so that those NSDictionary instances only contain a subset of the properties available on the Employee entity.

For more information about NSFetchRequest, see the class documentation.