Search code examples
iosxcodensfetchrequestnssortdescriptor

NSSortDescriptor with relationship


Got 3 Entities in my CoreData Models

Formations with a sections relationship to a Sections entity and chapters relationship with a Chapters entity.

So A Formation contains 1 or n sections containing 1 or n chapters

In my section Entity, there is a sortNB attribute (a kind of id), so I would like to sort my sections in my request.

I tried to do :

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Formations" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];


NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"sections.sortNB" ascending:YES];
[request setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObjects:@"sections", nil]];
[request setSortDescriptors:[NSArray arrayWithObject:sort]];


NSArray *forms = [[_managedObjectContext executeFetchRequest:request error:nil]mutableCopy];

But got an error :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'

How can I proceed ?

I would like to insert same kind of number in my Chapters entity to sort it too, but first, let's resolve it for Sections :p

Thanks


Solution

  • Ok so I sort my objects not in my request but after using

    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"sortNB" ascending:YES]];
    
    NSArray *sortedRecipes = [[[formation sections] allObjects] sortedArrayUsingDescriptors:sortDescriptors];
    

    And it works.

    Thanks for your help.