objective-c - NSFetchedResultController。使用表达式/按条件计算 sectionNameKeyPath

标签 objective-c ios core-data nsfetchedresultscontroller

假设有一个名为 testTable 的表:

(NSNumber*) numValue
(NSString*) stringValue

那么假设里面大概有50条记录。 numValue 每条记录都不一样。 如果我像这样创建 NSFetchedResultController:

NSFetchRequest *request = [[NSFetchedResultsController alloc] 
                            initWithFetchRequest: request 
                            managedObjectContext: context 
                            sectionNameKeyPath: @"numValue" 
                            cacheName: @"testTable"]];

那我会得到 50 个部分。

我的问题是: 我怎样才能得到2个部分: 第一个包含 numValue 小于某个 x 的记录,第二个包含 numValue 大于相同 x 的记录。

对于 x = 15,它可能看起来像这样:

NSFetchRequest *request = [[NSFetchedResultsController alloc] 
                            initWithFetchRequest: request 
                            managedObjectContext: context 
                            sectionNameKeyPath: @"numValue > 15" 
                            cacheName: @"testTable"]];

可能的解决方案是:

  1. 我们可以像@Dima 所说的那样编辑我们的实体。
  2. numberOfSectionsInTableView: 中,我们可以只查看部分名称并将它们与 x 进行比较。然后我们可以在 tableView:numberOfRowsInSection: 中查看这些名称并计算我们需要的内容。但这也感觉很脏。比第一种方法更好,但仍然如此。

更新: 好吧,我几乎想出了第三种方法来做到这一点。感谢@Dima 的链接。 这是代码:

[self setFetchedResultsController: [[NSFetchedResultsController alloc]
    initWithFetchRequest: request 
    managedObjectContext: context 
    sectionNameKeyPath: [NSString stringWithFormat: @"numValue.compare(%f)", x]];

但 KVC 合规性存在问题: 带有参数的方法(选择器)显然不符合 KVC。 有解决方法吗?

最佳答案

参见 this回答作为引用。

向实体添加可选属性并使其成为 transient 属性。

然后创建一个getter(假设你的属性叫做sectionGroup)

- (NSNumber *) sectionGroup
{
  [self willAccessValueForKey:@"sectionGroup"];
  NSNumber *group = [NSNumber numberWithInt:0];
  if(numValue > 15)
  {
    group = [NSNumber numberWithInt:1];
  }
  [self didAccessValueForKey:@"sectionGroup"];
  return group;
}

现在,您可以使用 sectionGroup 作为您的 sectionNameKeyPath。

关于objective-c - NSFetchedResultController。使用表达式/按条件计算 sectionNameKeyPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11433759/

相关文章:

iphone-sdk-3.0 - 如何通过对象图对托管对象的 NSMutableArray 进行排序

iphone - 为什么在iOS中可以使用object但是NSLog(@"%@",object)会导致bad memory access?

ios - 如何从同一单元格中删除 UITableViewCell?

iphone - EKEvent 在 iOS5 中损坏?

ios - 图片建议不起作用 Xcode 10

ios - 无法在 XCode 7 beta 2 中调试

ios - 接收者类型是前向声明

iphone - 使用 Phonegap 复制/粘贴剪贴板 iPhone

ios - SceneKit - 音频在我第一次播放声音时导致 cxa_throw 延迟

ios - 核心数据 : Correct way to update within a NSUrlRequest