我在我的核心数据模型中定义了一个名为“RemainingGaneProjections”的提取请求。我想执行该获取请求并按实体的属性之一对结果进行排序。我的代码如下所示:
NSFetchRequest *projectionsRequest = [model fetchRequestTemplateForName:@"RemainingGameProjections"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"confidence" ascending:NO];
[projectionsRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
当我尝试执行此代码时,它崩溃并显示以下消息:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't modify a named fetch request in an immutable model.'
我已经在调试器中确认当我在我的 NSFetchRequest 上执行 setSortDescriptors 方法时会发生此崩溃。我一直无法弄清楚为什么会这样。
对这里发生的事情有什么解释吗?在检索需要排序的数据时,我应该使用另一种方法吗?
最佳答案
我自己在所有地方的 Apple 文档中找到了答案。因为我的提取请求没有替换参数,所以我使用了 fetchRequestTemplateForName 方法而不是 fetchRequestFromTemplateWithName。事实证明,Core Data 编程指南是这样说的:
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").
我修改了我的获取请求初始化来执行此操作:
NSFetchRequest *projectionsRequest = [[model fetchRequestTemplateForName:@"RemainingGameProjections"] copy];
现在一切正常。
关于objective-c - 将排序描述符应用于从模板创建的 NSFetchRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7425713/