2014-02-24 103 views
0

循环我有一个CoreData(SQLite的)数据模型中的xcode像这样:验证数据,并且通过的NSSet

Friends Table 
    email 
    name 
    username 
    belongsToGroups 

Groups Table 
    title 
    peopleInGroup 

所以belongsToGroupspeopleInGroups被彼此多到多的关系,两者由NSSet表示在代码中。

我该如何查询中的人群,反之亦然? (我是CoreData的新手)

+1

查询什么?你有什么开始(一个人/没有?),你想找什么? – Wain

+0

我想看看我的人是否已经属于一个组,如果不加入他,或者忽略它 – cdub

回答

0

随着coredata,你可以简单地做到这一点。假设我们在Groups Table(group)上有一个对象,你想得到属于group的所有朋友,你可以这样做:

[group。 peopleInGroup allObjects]

更多细节:

  1. 获取组经由标题
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; 

}

  1. 获取组的所有朋友

    NSMutableArray * friends = [NSMutableArray alloc] init]; [friends addObjectsFromArray:[group。 peopleInGroup allObjects]];

+0

是否有更多的代码来设置它 – cdub

+0

你不需要做一个nsfetchrequest和所有的第一? – cdub

+0

是的,我们需要通过标题在组表上获取NSFetchRequest,然后我们获得组的所有成员。可以吗? –