Batch faulting in a to-many relationship for a collection of objects
- by indragie
Scenario:
Let's say I have an entity called Author that has a to-many relationship called books to the Book entity (inverse relationship author). If I have an existing collection of Author objects, I want to fault in the books relationship for all of them in a single fetch request.
Code
This is what I've tried so far:
NSArray *authors = ... // array of `Author` objects
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Book"];
fetchRequest.returnsObjectsAsFaults = NO;
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"author IN %@", authors];
Executing this fetch request does not result in the books relationship of the objects in the authors array being faulted in (inspected via logging).
I've also tried doing the fetch request the other way around:
NSArray *authors = ... // array of `Author` objects
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Author"];
fetchRequest.returnsObjectsAsFaults = NO;
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", authors];
fetchRequest.relationshipKeypathsForPrefetching = @[@"books"];
This doesn't fire the faults either. What's the appropriate way of going about doing this?