谓词到多对多关系核心数据



我在核心数据模型中有两个实体:A <<--->> B
实体B有一个属性名,它是一个字符串对象和一个关系AObjects到a;相反,实体A与b有一个关系。
现在我想要得到与实体连接的所有对象的列表,然后,我想要在标签中显示它们的名称。

这可能吗?我知道CoreData不支持多对多关系…
谢谢!

我想你可能没有完全描述你的情况,因为Core Data当然绝对支持多对多关系。我怀疑你的意思是NSFetchedResultsController不支持多对多关系?就我所能确定的而言,这是正确的。 (Edit:可以使用NSFetchedResultsController与多对多关系…只是怎么做不是很明显。

要在没有NSFetchedResultsController的情况下做到这一点,识别/获取你感兴趣的A实体,然后遍历你感兴趣的关系。因此,如果您已经知道您对特定的a对象感兴趣,我将其命名为aobject,类名为a和B,您可以使用点语法和快速枚举遍历关系,使用如下所示:

for (B *theBObject in theAObject.BObjects) {
    NSLog(@"theBObject.name: %@.", theBObject.name);
    // Run whatever code you want to here on theBObject.
    // This code will run once for each B Object associated with theAObject 
    // through the BObjects relationship.
}

或者,您可以设置一个获取请求来获取您感兴趣的一组AObjects,然后遍历每个对象的boject关系。这是一种多对多关系,没有任何区别……每个aobject将返回在其BObjects关系中的所有B对象。

后来

现在,您说要获取所有名称,并将其显示在标签中。让我们为你分析一下:

NSString *myLabel = null;
// You may of course want to be declaring myLabel as a property and @synthesising
// it, but for the sake of a complete example we'll declare it here which means 
// it will only have local scope.
for (B *theBObject in theAObject.BObjects) {
    myLabel = [myLabel stringByAppendingString:theBObject.name];    
    // Add a line break in the string after each B object name.
    myLabel = [myLabel stringByAppendingString:@"n"];
}
// Do something with your myLabel string to set your desired label.

您可以尝试这样的谓词:

NSPredicate* fetchPredicate = [NSPredicate predicateWithFormat: @"any A objects = %@", [nsmanagedobjecd of an A]];

最新更新