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:
-location开发者_开发百科Name (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'
// 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).
I just noticed that in your screen shot, your LocationActivities
entity is actually spelled LocationAtivities
(note the missing "c").
That is enough to wreck your graph. Any predicate that looks for LocationActivities
will fail.
Errors like this make me hate programming. I seem to spend more time tracking down typos than I do fixing design errors.
As an aside, you need to stop thinking in terms of tables and queries for Core Data. In Core Data those specifics of only the sqllite persistent store and you never see them or deal with them.
Entities are not tables and relationships are not linking tables. Trying to cram the object model into an SQL in your head will lead you to grief because Core Data does not work like SQL.
精彩评论