Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting a to-many relationship when calling NSFetchRequest
    text
    copied!<p>I have two entities. Client and Project. A Client has many Projects, but a Project can only be assigned to one Client. This has been designed with the datamodel.</p> <ul> <li>Client entity has attribute <em>clientName</em> and relationship to-many <em>projects</em> </li> <li>Project entity has attribute <em>projectName</em> and relationship to-one <em>client</em></li> </ul> <p>I want to retrieve <strong>all</strong> Clients from my ManagedObjectContext where the Clients are sorted by <em>clientName</em> ascending and then have the Projects for that Client by <em>projectName</em> ascending.</p> <p>This is my current code, where I KNOW it is wrong since there is no way for Client entity to sort by the <em>projectName</em>:</p> <pre><code>NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Client" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // Creating the sort descriptors array. NSSortDescriptor *clientSort = [[NSSortDescriptor alloc] initWithKey:@"clientName" ascending:YES]; // this next row is super wrong NSSortDescriptor *projectSort = [[NSSortDescriptor alloc] initWithKey:@"projectName" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:clientSort. projectSort, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSError *error; // Assign to NSArray of ViewController clientArray = [[managedObjectContext executeFetchRequest:fetchRequest error:&amp;error] mutableCopy]; </code></pre> <p>After this has been assigned to <code>clientArray</code>, I want to go to another method and ask for the Projects and have them in ascending order. Example:</p> <pre><code>Client *temp = (Client *)[clientArray objectAtIndex:selectedClient]; NSArray *projectsArray = [temp.projects allObjects]; Project *project = [projectsArray objectAtIndex:selectedProject]; return project.projectName; </code></pre> <p>I saw an implementation where they got the Clients and then sorted the projects manually... But this is kind of expensive and I'm hoping there are functions to do this when the Context gets queried.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload