4

Hi would like to know how to specify a FetchRequest where i can order the objects in a relationship.

   |  Parent         |        | Child        |
   |     - name      |------->|   - name     |
   |     - position  |        |   - position |

For example if i have a parent table that contains a position attribute and has a one to many relationship with a child table that has a also has a position attribute. How do i return the parent objects (ordered by position) that contain the child objects ordered by position.

e.g

parent 1
   child 1
   child 2
   child 3

parent 2
   child 15
   child 16

parent 3
   child 22
   child 23
   child 24

Obviously the below code will order the parent objects correctly, but how do i make the child objects that are returned with the each parent to be in the correct order

    NSFetchRequest* fetchReqest = [[NSFetchRequest alloc] init];

    NSEntityDescription* entity = [NSEntityDescription entityForName:@"parent"  inManagedObjectContext:managedObjectContext];
    [fetchReqest setEntity:entity];  

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                        initWithKey:@"position" ascending:YES];
    [fetchReqest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    NSArray* parentsThatContainChildren =  [managedObjectContext executeFetchRequest:fetchReqest error:nil];

Cheers

user346443
  • 4,672
  • 15
  • 57
  • 80

1 Answers1

4

There's 2 strategies to this:

  1. Perform a separate fetch request for the children with the NSSortDescriptor. Pro: you keep this in the FetchController. Con: multiple fetch requests can slow you down
  2. Sort the returned children in the NSArray* parentsThatContainChildren.

For #2, you can check this out :

NSSortDescriptor *positionSort = [NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES];

NSArray *children = [[parent.children allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:positionSort]];
Community
  • 1
  • 1
Dominic Tancredi
  • 41,134
  • 7
  • 34
  • 50