简化多次获取请求

时间:2012-01-09 08:41:43

标签: objective-c core-data

我有这个核心数据模型层次结构,彼此之间具有相应的关系:

公司 - > DIVISIONS - >部门 - >员工 - >照片

如果我想收集分部的所有员工照片,我需要:

  1. 抓取以查找哪些部门有分部。
  2. 抓取以找到该部门每个部门的所有员工
  3. 获取每位员工以查找是否有照片....
  4. 将照片添加到阵列。
  5. 在循环中有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;
    
    }
    

    任何人都可以建议更好的解决方案或如何完成此类请求?

1 个答案:

答案 0 :(得分:2)

假设您为所有内容设置了反向关系:

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