I have a NSManagedObject
with related objects. The relation is described by a keyPath.
Now I want to display these related objects in a table view. Of course I could just take the NSSet
with these objects as a data source, but I'd prefer to refetch the objects with a NSFetchedResultsController
to benefit from its features.
How can I create a predicate that describes these objects?
To display the related objects of a given object with a fetched results controller, you would use the inverse relationship in the predicate. For example:
To display the children related to a given parent, use a fetched results controller with the following fetch request:
Parent *theParent = ...;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Child"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parent = %@", theParent];
[request setPredicate:predicate];
For nested relationships, just use the inverse relationships in inverted order. Example:
To display the streets of a given country:
Country *theCountry = ...;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Street"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city.country = %@", theCountry];
[request setPredicate:predicate];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With