Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core-Data: Predicate for To-Many Relationships

I have a CoreData model with 4 entities.

Model screenshot -> http://img96.imageshack.us/img96/7857/screenshot20100209at182.png

State

-StateName

Location:

-locationName (attribute)

-locationDescription

-locationActivities (relatinship)

-state (relationship)

LocationActivities:

-location (relationship)

-activity (relationship)

Activities

-activityName(attribute)

-locationsActivities (relationship)

How can i write a query that selects all Locations that have

(activity = 'Golf' OR activity = 'Swimming') AND state = 'LA'

like image 630
Jonathan Ramirez Avatar asked Feb 09 '10 20:02

Jonathan Ramirez


People also ask

What is relationship in core data?

Inverse relationships enable Core Data to propagate change in both directions when an instance of either the source or destination type changes. Every relationship must have an inverse. When creating relationships in the Graph editor, you add inverse relationships between entities in a single step.

What is core data stack?

As I mentioned earlier, the Core Data stack is the heart of Core Data. It's a collection of objects that make Core Data tick. The key objects of the stack are the managed object model, the persistent store coordinator, and one or more managed object contexts.


1 Answers

// With some NSManagedObjectContext *moc
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"Location"
                               inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:
                       @"(locationActivities.activity.activityName == %@ OR 
                          locationActivities.activity.activityName == %@) AND 
                         state.stateName == %@",
                       @"Golf", @"Swimming", @"LA"]];
NSError *error;
NSArray *results = [moc executeFetchRequest:request error:&error];

Basically, do a Core Data fetch as normal, then build the appropriate predicate to filter the results (as described in the Predicate Programming Guide).

like image 177
Tim Avatar answered Sep 27 '22 22:09

Tim