2014-11-20 63 views
0

我有我的CoreData型号一个问题: enter image description here过滤CoreData获取与parentEntities

如果我有很多TopObjects,并希望获取所有子对象的具有特定对象的关系,如何过滤我的导致获取谓词。通常我会设置一个谓词,如“top = refObject”。但抽象实体SubObject与“top”没有关系,只是实体本身。

如果我尝试将关系仅添加到父实体“SubObject”,我失去了TopEntity中的直接关系。

有人可以给我一个提示吗?

+0

由于每个子实体都有一个“顶”的关系,为什么不把它放在抽象的父实体? – 2014-11-21 00:56:40

+0

因为我需要顶部的3个不同的关系用于我的数据结构。如果我把它放在父类中,我只和一个SubObject有一个关系。 – 2014-11-21 07:09:55

回答

0

不确定是否有条件地在谓词中指定关系(这将允许单个获取请求执行此操作),但下面可能是一种获取多次获取中所需对象的方法。这个想法是遍历托管对象模型中的所有实体,并检查它们是否具有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 
    } 
} 
+0

处理这个问题的好方法。但我的tableview应该与FetchedResultsController和Delegate一起工作。所以我不想使用数组作为数据源。这是问题所在。我希望有一种方法可以处理我没有提到过的单个FetchedResultsController中的所有subs。 – 2014-11-22 22:43:47