将排序描述符应用于从模板创建的NSFetchRequest [英] Applying sort descriptor to NSFetchRequest created from template
问题描述
我在我的核心数据模型中定义了一个称为RemainingGaneProjections的获取请求。我想执行该获取请求并按照实体的一个属性对结果排序。我的代码看起来像这样:
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.'
我在调试器中确认,当我在NSFetchRequest上执行setSortDescriptors方法时,发生此崩溃。我还未能找出为什么会发生这种情况。
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?
推荐答案
记录所有地方。因为我的读取请求没有替换参数,我使用fetchRequestTemplateForName方法,而不是fetchRequestFromTemplateWithName。事实证明,Core Data编程指南说明:
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:
如果模板没有替换变量,则必须: p>
If the template does not have substitution variables, you must either:
- 使用fetchRequestFromTemplateWithName:substitutionVariables:并传递
nil作为变量参数; - 使用fetchRequestTemplateForName:和
复制结果。如果您尝试使用
fetchRequestTemplateForName:返回的获取请求,则会生成一个异常(不能
在不可变模型中修改命名的提取请求)。
我修改了我的抓取请求初始化操作:
I modified my fetch request initialization to do this:
NSFetchRequest *projectionsRequest = [[model fetchRequestTemplateForName:@"RemainingGameProjections"] copy];
现在一切正常。
这篇关于将排序描述符应用于从模板创建的NSFetchRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!