Applying sort descriptor to NSFetchRequest created from template

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!