small medium large xlarge

Back to: All Forums  Core Data
04 May 2009, 13:57
Greg Robertson (21 posts)

How do I create a search predicate to include an attribute of another entity to which there is a relationship?

here is a simplified example of what I mean:

Entity Meal with the attributes: type and foods, foods has a one to many relationship with the Entity Food

Entity Food with attributes: name and meal, meal has an inverse relationship with the entity Meal

How can I create an NSPredicate to select all the distinct foods based on the Meal attribute type?

I was thinking about something like:

// standard setup
       NSFetchRequest *request = [[NSFetchRequest alloc] init];
       NSEntityDescription *entity = [NSEntityDescription entityForName:@"Food" inManagedObjectContext:userManagedObjectContext];
       [request setEntity:entity];

// sort by name
       NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
       NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortByName, nil];
       [request setSortDescriptors:sortDescriptors];

// this is where I am not sure
// *********************
       NSPredicate *searchType = [NSPredicate predicateWithFormat:@"type=%d", TypeID];
       [request setPredicate:searchType];
       [request setResultType:NSDictionaryResultType];
       [request setReturnsDistinctResults:YES];
       [request setPropertiesToFetch:[NSArray arrayWithObjects:@"name", @"meal.type", nil]];
// ***********************

// the rest is pretty standard stuff to setup an array
       [sortDescriptors release];
       [sortByName release];
       NSError *error;
       NSMutableArray *mutableFetchResults = [[userManagedObjectContext executeFetchRequest:request error:&error] mutableCopy];
       if (mutableFetchResults == nil)
               // Handle the error.
       [self setMyArray:mutableFetchResults];
       [mutableFetchResults release];
       [request release];


Can I use Obj-C 2.0 dot notation in an NSPredicate? If not how should I setup the predicate?



27 Jul 2009, 06:16
Marcus S. Zarra (284 posts)

NSPredicate uses KVC which traverses objects using a dot notation similar to dot syntax. Note that these are two VERY different things with similar results. Therefore you can cross relationship boundaries in a predicate using it. Your predicate should look as follows:

NSPredicate *searchType = [NSPredicate predicateWithFormat:@"meal.type=%d", TypeID];

I would not set the setResultType to NSDictionary. You want to return NSManagedObjects.

You must be logged in to comment