Reputation: 1443
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:
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
Reputation: 7931
Assuming you setup inverse relationships for everything:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photos"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"employee.department.division = %@", division"];
Upvotes: 2