Ios NSFetchRequest, arrange child objects

Hi, I would like to know how to tell FetchRequest where I can order the objects in relation.

| 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 also has a position attribute. How to return parent objects (ordered by position) containing child objects ordered by position.

eg

 parent 1 child 1 child 2 child 3 parent 2 child 15 child 16 parent 3 child 22 child 23 child 24 

Obviously, the code below will correctly order the parent objects, but how to make the returned child objects with each parent 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]; 

Greetings

+4
source share
1 answer

There are 2 strategies for this:

  • Run a separate sample query for children using the NSSortDescriptor. Pro: you save this in the FetchController. Con: Multiple fetch requests may slow down.
  • Sort the returned children in NSArray * parentsThatContainChildren.

For # 2 you can check this :

 NSSortDescriptor *positionSort = [NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES]; NSArray *children = [[parent.children allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:positionSort]]; 
+4
source

All Articles