HusseinB
HusseinB

Reputation: 1341

Core Data fetching relationship objects

in my app i have two entities: Members and Lists. they both have a one-to-many relationships (member can have more than one list, list can have more than one member). now i want to fetch the lists belonging to a specific member. here is my code:

WSAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Lists" inManagedObjectContext:context];

[fetchRequest setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"has_members contains[cd] %@", [self.currentMember valueForKey:@"name"]]];

[fetchRequest setPredicate:predicate];

NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // Handle the error.
    NSLog(@"NO LISTS AVAILABLE IN REFRESH");
}

self.currentMember is a managed object of the user himself.

Note: member has name, (NSSet*) member_of_list

list has list_name, has-members

Problem: when i run the code it's breaking at the fetchedObjects array. i suspect that there is something wrong with the NSPredicate but i don't know where and how to fix it. can any one point out the problem?

Upvotes: 0

Views: 2432

Answers (1)

Dan Shelly
Dan Shelly

Reputation: 6011

First, the relationship you describe between Member (Calling an entity in a plural form is confusing) and List is many-to-many.

Second, instead of using CoreData's inherent object graph capabilities, you went and "rolled your own" relationship between the entities (you should use your interface builder to model a CoreData relationship between the two entities).

See HERE how to do that.

after you model your data, your predicate should look something like:

//Not tested
NSPredicate* p = [NSPredicate predicateWithFormat:@"ANY members = %@",self.currentMember];

DO NOT pass a formatted string to create the predicate, use NSPredicate formatting to substitute parameters or you will not be able to accomplish your goal (in most cases).

Upvotes: 3

Related Questions