0

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

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

4

2 回答 2

2

我认为您可能没有完全描述您的情况,因为 Core Data 当然绝对支持多对多关系。我怀疑您的意思可能是 NSFetchedResultsController 不支持多对多关系?据我所知,这是正确的。编辑:可以使用具有多对多关系的 NSFetchedResultsController ......如何做到这一点并不是很明显。)

要在没有 NSFetchedResultsController 的情况下执行此操作,请识别/获取您感兴趣的 A 实体,然后遍历您感兴趣的关系。因此,如果您已经知道您对特定的 A 对象感兴趣,我将调用 theAObject,使用类名 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.
}

或者,您可以设置一个 fetch 请求来获取一组您感兴趣的 AObjects,然后为它们中的每一个遍历 BOjects 关系。它是多对多关系没有任何区别......每个 AObjecct 将返回其 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.
于 2011-10-02T10:07:38.050 回答
0

您可以尝试这样的谓词:

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

于 2011-09-26T10:36:06.883 回答