【问题标题】:Filtering CoreData Fetch with parentEntities使用父实体过滤核心数据获取
【发布时间】:2014-11-20 23:06:35
【问题描述】:

我的 CoreData 模型有问题:

如果我有很多 TopObjects 并且想要获取与特定对象有关系的所有 SubObject,我如何在 fetch 谓词中过滤我的结果。 通常我会设置一个谓词,如“top = refObject”。但是抽象实体 SubObject 没有关系“top”,只有实体本身。

如果我尝试仅将关系添加到父实体“子对象”,我会丢失 TopEntity 中的直接关系。

谁能给我一个提示?

【问题讨论】:

  • 既然每个子实体都有top关系,为什么不把它放在抽象的父实体中呢?
  • 因为我的数据结构需要 Top 中的 3 个不同关系。如果我把它放在父对象中,我与某个子对象只有一种关系。

标签: xcode core-data


【解决方案1】:

不确定是否有一种方法可以有条件地在谓词中指定关系(这将允许单个提取请求执行此操作),但下面可能是一种在多次提取中提取您需要的对象的方法。想法是遍历托管对象模型中的所有实体,检查它们是否具有 TopObject 关系并且属于 SubObject 类,然后根据 topObject 获取它们。

for (NSEntityDescription *entityDescription in managedObjectModel)
{
    // Attempt to pull out the TopObject relationship
    NSRelationshipDescription *topRelationshipDescription = entityDescription.relationshipsByName[@"top"];

    // Test if the relationship points to the TopObject and if the entity is of the correct class
    if ([topRelationshipDescription.destinationEntity.name isEqualToString:@"TopObject"] &&
        [NSClassFromString(entityDescription.managedObjectClassName) isSubclassOfClass:[SubObject class]])
    {
        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:entityDescription.name];
        fetchRequest.predicate = [NSPredicate predicateWithFormat:@"top = %@", topObject];

        // fetch objects and add them to an array
    }
}

【讨论】:

  • 处理这个问题的好方法。但我的 tableview 应该与 FetchedResultsController 和 Delegate 一起使用。所以我不想使用数组作为数据源。这就是问题所在。我希望有一种方法可以处理我尚未提到的单个 FetchedResultsController 中的所有子项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
相关资源
最近更新 更多