CoreData:多对多关系

时间:2011-09-15 19:11:23

标签: core-data many-to-many nspredicate

我有两个对象,有多对多关系。

enter image description here

这是我的代码:

+ (NSSet *)activitiesSetForMember:(Members *)member inManagedObjectContext:(NSManagedObjectContext *)context{
NSSet *activitiesSet = nil;

NSFetchRequest *request = [[NSFetchRequest alloc] 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;   
}

如何从选定的Activities获取所有Member?我如何构建请求确实给我了?

1 个答案:

答案 0 :(得分:1)

正如您可能已经怀疑的那样,您的谓词有问题:

也许你因为你的关系命名方式而感到困惑。这些名字似乎表明存在一些概念上的混乱。我建议你重命名你的实体和关系:

Members         - Member
CompanyActivity - Activity
memberActivity  - activities
hasMembers      - members

有一个更好的解决方案。属性活动是否已经包含您想要的活动?因此:

activitiesSet = member.activities; // according to my naming scheme