Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend


What if instead of retrieving every instance of an Entity I just need those instances with a specific attribute. For instance, if the ExampleEntity listed above had an attribute called state which is an Integer and I wanted to find all of the entities that had a state of zero, I would alter the code above as follows:

NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"state == 0"];
NSEntity *entity = [NSEntityDescription entityForName:@"ExampleEntity"
[request setEntity:entity];
[request setPredicate:predicate];
NSError *error;

NSArray *result = [context executeFetchRequest:request error:"error];
NSAssert(result != nil, 
   ([NSString stringWithFormat:@"Error fetching entity: %@", error]));

The only change from the previous example is the addition of a NSPredicate to the NSFetchRequest. The NSPredicate is similar in functionality to the where clause of a SQL query. It is possible to create compound predicates as well as simple ones. By utilizing predicates it is possible to retrieve exactly the entities needed by the application.

  • + Share This
  • 🔖 Save To Your Account