【问题标题】:Filter hierarchy筛选层次结构
【发布时间】:2014-05-27 06:33:55
【问题描述】:

我正在使用 Core Data 编写一个应用程序,该应用程序必须维护一个具有 4 级层次结构的目录。

Category <--->> SubCategory <--->> Item <--->> SubItem

我有一个屏幕(表格/集合视图),其中ItemsCategorySubCategory 标题一起显示。项目可能是。 基本上我必须显示过滤目录。假设项目有一个名称,我想按名称过滤项目。

示例。

Category: Category 1
  SubCategory: SubCategory 1.1
    Items: [aaa, bbb, ccc, abc, abd, abg] 
  SubCategory: SubCategory 1.2
    Items: [aaa, bbb, ccc] 
Category: Category 2
  SubCategory: SubCategory 2.1
    Items: [123ab, 456ab, 123, 345, 456]

使用查询“ab”过滤后,我想查看以下对象:

Category: Category 1
  SubCategory: SubCategory 1.1
    Items: [abc, abd, abg] 
Category: Category 2
  SubCategory: SubCategory 2.1
    Items: [123ab, 456ab]

问题是:我不能对Category 使用获取请求,因为它只会显示包含满足条件的项目的类别,但不会过滤项目。 我可以直接获取Item 的过滤集合,但我必须重建结构Category - SubCategory - Item 并将其放入一些数组/字典等中。

有没有更好的方法来使用 CoreData 过滤深度嵌套的层次结构? 主要问题:有没有办法在对其根运行获取请求时获取深度嵌套对象树的叶子?

【问题讨论】:

  • 我很难理解您想要过滤项目的标准。您能否详细介绍一下子项如何影响获取请求
  • 添加示例和更新描述。
  • 你能把你用来过滤的fetch request贴出来吗?

标签: ios objective-c core-data hierarchy hierarchical-data


【解决方案1】:

您可以使用searchString 过滤items

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Item"];
NSPredicate *predicate = nil;

 if([_searchBar.text length] > 0){
    predicate = [NSPredicate predicateWithFormat:@"itemName CONTAINS[cd] %@", _searchBar.text];
}

if(predicate){
    [fetchRequest setPredicate:predicate];
}

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"itemName" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

如果您需要通过考虑categorysubCategory 对结果进行排序,您可以根据您的优先级使用更多的排序描述符,例如,

NSSortDescriptor *sortDescriptorCategory = [[NSSortDescriptor alloc]initWithKey:@"categoryName" ascending:YES];
NSSortDescriptor *sortDescriptorSubCategory = [[NSSortDescriptor alloc]initWithKey:@"subCategoryName" ascending:YES];
NSSortDescriptor *sortDescriptorItem = [[NSSortDescriptor alloc]initWithKey:@"itemName" ascending:YES];

[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptorCategory, sortDescriptorSubCategory, sortDescriptorItem, nil]];

【讨论】:

    【解决方案2】:

    您可以像这样用 '.' 分隔每个键...

    NSSortDescriptor *sortDescriptorSubCategory = [[NSSortDescriptor alloc]initWithKey:@"Category.SubCategory.Items" ascending:YES];
    

    然后,在 iOS 7 + 中

    [YOUR_ARRAY sortedArrayUsingDescriptors:@[sortDescriptorSubCategory]];
    

    或者,较旧的 iOS 版本

    [YOUR_ARRAY sortedArrayUsingDescriptors:[NSArray sortDescriptorSubCategory, nil]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多