Nimrod7
Nimrod7

Reputation: 1443

Simplifying Multiple Fetch Requests

I have this Core Data Model Hierarchy, with the respective relationships to each other:

COMPANY -> DIVISIONS -> DEPARTMENTS -> EMPLOYEES -> PHOTOS

If I want to collect all the employee photos from a division I need to:

  1. Fetch to find what departments have a division.
  2. Fetch to find all the employees in each department in the division
  3. Fetch each employee to find if there are photos....
  4. Add the photo to the array.

Which are 3 requests inside loops, performance wise is a disaster!

-(NSArray *)getPhotosForCategory: (NSManagedObject *)division {

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Divisions"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"division == %@", department];
    [request setPredicate:predicate];

    NSError *error;
    divisions = [managedObjectContext executeFetchRequest:request error:&error];

    NSMutableArray *employeesArray = [[NSMutableArray alloc] init];

    for (NSManagedObject *object in divisions) {

        NSFetchRequest *employeesRequest = [NSFetchRequest fetchRequestWithEntityName:@"Employees"];
        NSPredicate *employeesPredicate = [NSPredicate predicateWithFormat:@"department == %@", object];
        [employeesRequest employeesPredicate];

        NSArray *employees = [managedObjectContext executeFetchRequest:employeesRequest error:&error];

        [employeesArray addObjectsFromArray:places];

    }

    NSMutableArray *photosArray = [[NSMutableArray alloc] init];

    for (NSManagedObject *object in employeesArray) {

        NSFetchRequest *photosRequest = [NSFetchRequest fetchRequestWithEntityName:@"Photos"];
        NSPredicate *photosPredicate = [NSPredicate predicateWithFormat:@"employee == %@", object];
        [photosRequest setPredicate:photosPredicate];

        NSArray *photos = [managedObjectContext executeFetchRequest:photosRequest error:&error];

        [photosArray addObjectsFromArray:photos];

    }

    return photosArray;

}

anyone can suggest a better solution or how such requests can be done?

Upvotes: 1

Views: 807

Answers (1)

agilityvision
agilityvision

Reputation: 7931

Assuming you setup inverse relationships for everything:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photos"];    
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"employee.department.division = %@", division"];

Upvotes: 2

Related Questions