核心数据 - 按关系选择

时间:2014-11-07 18:28:41

标签: ios objective-c iphone core-data swift

我在FatherSon实体之间存在一对多的关系,其中Father可能没有或Son。使用Core Data,如何根据我的搜索Son获取所有Father

例如:我有一个拥有Father的{​​{1}} 1。我需要获取所有Id Son FatherId 1。

2 个答案:

答案 0 :(得分:1)

这里有一个使用NSManagedObject的例子(子类化更容易)。

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Father" inManagedObjectContext:your_managedObjectContext]];
// You speak about you use Id, but is word reserved better use resourceId or something like that
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"resourceId=1"];
[request setPredicate:predicate];
NSArray *result = [your_managedObjectContext executeFetchRequest:request error:nil];
NSManagedObject *father_Id1 = [result firstObject];
NSSet *sons = [father_Id1 valueForKey:@"theNameOfYourRelationshipSons"];

答案 1 :(得分:1)

这是一个快速代码,可以获取所有拥有id = 5

父亲的Sons
let fetchRequest = NSFetchRequest(entityName: "Son")
fetchRequest = NSPredicate(format: "father.id == %@", argumentArray: [id])
let fathers = context.executeFetchRequest(fetchRequest, error: nil) as? [Father]