Search code examples
ioscocoa-touchcore-datansfetchrequest

Nested core data fetch


I have a core data DB with multiple entities. There is a parent entity called "Person" which has many "Friends", "Friends" have many "Activities", and "Activities" have "Types" ("Types has a to-many relationship to "Activities"). What I'm trying to achieve is filtering all the "Person" entities by "Types". A user would be tapping on a "Type" and then I would refresh my table and filter the "Person" entities that are displayed by the "Types" that are associated with them.

Currently I'm thinking I have to use a compound predicate but I'm completely sure how to go about it. So far all I've done is printed out the values I've wanted by looping through my fetchedObjects like so:

NSArray *persons = self.fetchedResultsController.fetchedObjects;


    for (JIPerson *person in persons) {
        JIFriend *friend = person.friends.anyObject;
        JIActivity *activity = friend.activities.anyObject;
        JIType *type = activity.type;
        NSLog(@"%@", type.name);

    }

This prints out the values correctly, but I need to filter my table using these values. How can I achieve that?


Solution

  • Seems like I got it. Using NSPredicate you can traverse a deep relationship like this using dot notation. My implementation went as follows:

    - (void)filterPersonByType:(NSString *)typeName {
    
        NSPredicate *typePredicate = [NSPredicate predicateWithFormat:@"ANY friends.activities.type.name CONTAINS[cd]%@", typeName];
    }