Reputation: 629
I have a Problem with my CoreData Model:
If i have a lot of TopObjects and want to fetch all SubObject's which have a relationship to a specific object, how can i filter my results in the fetch predicate. normally i would set a predicate like "top = refObject". but the abstract entity SubObject has no relationship "top", just the entities itself.
If i try to add the relationship only to the parent entity "SubObject" i lost the direct Relations in the TopEntity.
Can anybody give me a hint ?
Upvotes: 0
Views: 97
Reputation: 1671
Not sure if there's a way of conditionally specifying a relationship in the predicate (which would allow a single fetch request to do this), but below is possibly a way to fetch the objects you need in multiple fetches. The idea is to iterate through all of the entities in the managed object model and check if they have the TopObject relationship and are of the SubObject class, then fetch them based on the 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
}
}
Upvotes: 0