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 confirmed 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With