本文介绍了CoreData:多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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





这里是我的代码:

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

NSFetchRequest * request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@CompanyActivityinManagedObjectContext: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ãoexiste ao tipo de Membro
if(!error&&!activitiesSet)
NSLog(@Error:会员没有活动相关。

return activitiesSet;
}

如何获得所有 c $ c>从选定的会员

解决方案

因为你可能已经怀疑,你的谓词有问题: / p>

也许你很困惑,因为你命名你的关系的方式。这些名字似乎表明有一些概念上的混乱。让我建议您像这样重命名您的实体和关系:

 会员 - 会员
CompanyActivity - 活动
memberActivity - activities
hasMembers - members

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

  activitiesSet = member.activities; //根据我的命名方案


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 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;
}

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

这篇关于CoreData:多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 09:13