Issue with setting NSSortDescriptor key in NSFetch

2020-07-17 17:01发布

问题:

With respect to the above relationship diagram, Earlier, I had a too many relationship between Assignment and Question entity and this is broken to fix a question ordering issue.

Now the relationship to Assignment to Question is through a join table AssignmentQuestion.

Idea here was to sort the question based on the questionOrderIndex property of the AssignmentQuestion table.

I am fetching the assignment questions through a NSFetchResultController. I have written a predicate to fetch the questions accordingly. But since I want the questions to be sorted based questionOrderIndex, my sort key for the sort descriptor through question entity is assignmnetQuestion.questionOderIndex.

But with this sort key, I am getting an exception: "Exception = to-many key not allowed here". Upon investigation, I found that it is because of "one to many" relation from Question to AssignmentQuestion table.

My questions are:

1) How to set the sort key for a Sort descriptor based on questionOrderIndex?

2) Do we really need to have a join table here in core data to sort the questions in order?

Predicate to fetch Questions:

NSString *predicateString = [NSString stringWithFormat:@"self.evaluationQuestion.assignmentEvaluation.assignmentId == %@", @"1"]; 

回答1:

If you don't need to listen for changes on the questions (external to your view controller), you could fetch the the AssignmentQuestion entities instead, and prefetch the attached questions.
later, in your view controller, instead of using the AssignmentQuestion entities, use their prefetched question relationship

//code not tested
NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"AssignmentQuestion"];
[request setPredicate:[NSPredicate predicateWithFormat:@"assignmentEvaluation.assignmentId == %@",assignmentId]];
[request setRelationshipKeyPathsForPrefetching:@[@"question"]];
[request setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"questionOrderIndex" ascending:YES]]];

also see here