2014-11-20 53 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