I have a CoreData (SQLite) datamodel in xcode like so:
Friends Table
email
name
username
belongsToGroups
Groups Table
title
peopleInGroup
So the belongsToGroups
and peopleInGroups
is a many-to-many relationship with each other, both represented by NSSet
in the code.
What do I use to query the NSSet
for people in my groups and vice versa? (I'm new to CoreData)
With coredata, you can do it simple. Assume we have one object on Groups Table ( group), you want to get all friends belong to group, you can do:
[group. peopleInGroup allObjects]
For more detail:
NSError* error = nil; NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init]; NSPredicate *predicate; NSEntityDescription *entity; NSArray *fetchedObjects; Group* group; entity = [NSEntityDescription entityForName:[NSString stringWithFormat:@"%@",[Group class]] inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(title like[c] \"%@\")" ,title]]; [fetchRequest setPredicate:predicate]; fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; if (fetchedObjects.count > 0) { group = [fetchedObjects lastObject]; } return group;
}
NSMutableArray* friends = [NSMutableArray alloc] init]; [friends addObjectsFromArray:[group. peopleInGroup allObjects]];