CoreData: many-to-many relationship
I have 2 objects, with many to many relationships.
Here's my code:
+ (NSSet *)activitiesSetForMember:(Members *)member inManagedObjectContext:(NSManagedObjectContext *)context{
NSSet *activitiesSet = nil;
NSFetchRequest *request = [[NSFetchRequest al开发者_JAVA技巧loc] init];
request.entity = [NSEntityDescription entityForName:@"CompanyActivity" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:@"hasMembers contains %@", member];
NSError *error = nil;
activitiesSet = [[context executeFetchRequest:request error:&error] lastObject];
[request release];
NSLog(@"count: %d", [activitiesSet count]);
//se o array vem vazio (nil), não existe a o tipo de Membro
if (!error && !activitiesSet)
NSLog(@"Error: Member has no Activities related.");
return activitiesSet;
}
How can I get all the Activities
from a selected Member
? How can I construct the request do give me that?
As you probably already suspected, something is wrong with your predicate:
Perhaps you are confused because of the way you named your relationships. The names seem to indicate that there is some conceptual muddiness. Let me suggest that you rename your entities and relationships like this:
Members - Member
CompanyActivity - Activity
memberActivity - activities
hasMembers - members
There is a better solution. Does not the attribute activities already contain exactly the activities you want? Thus:
activitiesSet = member.activities; // according to my naming scheme
精彩评论