Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying sort descriptor to NSFetchRequest created from template

Tags:

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?

like image 579
Tim Dean Avatar asked Sep 15 '11 04:09

Tim Dean


1 Answers

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:

  1. Use fetchRequestFromTemplateWithName:substitutionVariables: and pass nil as the variables argument;
  2. 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.

like image 66
Tim Dean Avatar answered Sep 21 '22 20:09

Tim Dean