Applying sort descriptor to NSFetchRequest created from template
I have a fetch request defined within my core data model called "RemainingGaneProjections". I want to execute that fetch request and sort the results by one of the entity's attributes. My code looks like this:
NSFetchRequest *projectionsRequest = [model fetchRequestTemplateForName:@"RemainingGameProjections"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"confidence" ascending:NO];
[projectionsRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
When I try to execute this code it crashes with the following message:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't modify a named fetch request in an immutable model.'
I have con开发者_Python百科firmed in the debugger that this crash happens when I execute the setSortDescriptors method on my NSFetchRequest. I haven't been able to figure out why this happens.
Any explanations for what is happening here? Is there another approach I should be using when retrieving data that needs to be sorted?
I found the answer myself in the Apple documentation of all places. Because my fetch request has no substitution parameters, I used the fetchRequestTemplateForName method instead of fetchRequestFromTemplateWithName. As it turns out, the Core Data programming guide says this:
If the template does not have substitution variables, you must either:
- Use fetchRequestFromTemplateWithName:substitutionVariables: and pass nil as the variables argument;
- Use fetchRequestTemplateForName: and copy the result. If you try to use the fetch request returned by fetchRequestTemplateForName:, this generates an exception ("Can't modify a named fetch request in an immutable model").
I modified my fetch request initialization to do this:
NSFetchRequest *projectionsRequest = [[model fetchRequestTemplateForName:@"RemainingGameProjections"] copy];
and now everything works as expected.
From Apple documentation:
NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
NSSortDescriptor *hireDateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"hireDate" ascending:YES];
NSArray *sortDescriptors = @[ageDescriptor, hireDateDescriptor];
NSArray *sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html
精彩评论