objective-c - 将排序描述符应用于从模板创建的 NSFetchRequest

标签 objective-c core-data

我在我的核心数据模型中定义了一个名为“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:

  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").

我修改了我的获取请求初始化来执行此操作:

NSFetchRequest *projectionsRequest = [[model fetchRequestTemplateForName:@"RemainingGameProjections"] copy];

现在一切正常。

关于objective-c - 将排序描述符应用于从模板创建的 NSFetchRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7425713/

相关文章:

objective-c - 根据数字重组 NSDictionary 键

ios - 检测已取消的 iTunes 登录警报以进行应用内购买

multithreading - 敲击按钮后应用程序崩溃

iphone - 添加新版本的核心数据模型?

swift - 在 Swift 中编写自定义访问器方法

objective-c - 如何防止Xcode每次都重建项目

Objective-C:如何将对象作为 block 参数传递给需要其基类的方法?

ios - 更新位置时 map View 跨度发生变化

Swift 撤消功能,先前声明的变量始终为空

ios - 在与父实体有关系的子 NSManagedObjectContext 中创建实体