views:

44

answers:

1

I have setup a data model where Student Entity has a name a 1-to-many relationship with Subject. Each Subject that he attends has a number of Class Times.

The code below sorts it, based on the Student name, this is straight forward.

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

What I want to do is sort it so that it is sorted on next Class time each Student needs to attend. So the display will be Student and sorted on the time of the next class. Any ideas?

I've tried the following

    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Student" inManagedObjectContext:managedObjectContext]];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(subjects.time > %@)", [NSDate date]]];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

I get the error "'to-many key not allowed here'", then I tried setRelationshipKeyPathsForPrefetching: but that didn't fetch the to-many-relationship of subjects. Any ideas?

A: 

This is the process:

Try this. Fetch Students. Then, for each student, fetch 'time' from Class, 'greater than or equal to current time' for Student (in predicate format), sorted by 'time'. Display details. If you put this in a loop, you have your answer.

Jordan
'time' is an attribute of Class. So the flow should go something like, fetch 'name' from Student. Fetch all 'time' from Class for that Student. Sort the 'time' to find the next class time (from now). Then sort all Students based on the next class time.
munchine
@munchine has it right.
Jordan
I'm struggling to get the code for this to work, hence the question, can someone help me?
munchine
Try this. Fetch Students. Then, for each student, fetch 'time' from Class, 'greater than or equal to current time' for Student (in predicate format), sorted by 'time'. Display details. If you put this in a loop, you have your answer.
Jordan
Do you have some code to show me how this should work. I am struggling to get the second fetch to work.
munchine
I'd have to work up the code. Not something I have the time to do right now. If you post your project on a downloadable site in a zip file , I'll have a look, or email me.
Jordan