我有这个核心数据模型层次结构,彼此之间具有相应的关系:
公司 - > DIVISIONS - >部门 - >员工 - >照片
如果我想收集分部的所有员工照片,我需要:
在循环中有3个请求,性能明智是一个灾难!
-(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;
}
任何人都可以建议更好的解决方案或如何完成此类请求?
答案 0 :(得分:2)
假设您为所有内容设置了反向关系:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photos"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"employee.department.division = %@", division"];