【问题标题】:is it possible to get distinct results when using an NSFetchedResultsController?使用 NSFetchedResultsController 时是否可以获得不同的结果?
【发布时间】:2011-10-22 01:12:05
【问题描述】:

我有一个产品搜索来搜索我的产品所在的 ProductCategories,有时我的产品属于多个类别,这给了我重复的结果。我不想直接搜索产品表,因为有几个产品有多种尺寸但基本上是相同的产品。

有没有办法使用 NSFetchedResultsController 获得不同的搜索结果?

【问题讨论】:

    标签: objective-c iphone core-data nsfetchedresultscontroller


    【解决方案1】:

    您需要使用 NSPredicate(请参阅 Predicate Programming Guide

    这很复杂,但您可以使用 SUBQUERY 来完成

    【讨论】:

    • ferdil – 你能详细说明你的答案吗?
    【解决方案2】:

    创建NSFetchRequest 时,您可以使用-setReturnsDistinctResults: 并将其设置为YES

    【讨论】:

    • 要使用它,您还必须设置 NSFetchedResultsController 不喜欢的 setResultType:NSDictionaryResultType
    • @Slee:更准确地说:FRC 不支持 NSDictionaryResultType。
    【解决方案3】:

    是的,你可以...

    注意方法

    - (NSFetchedResultsController *)fetchedResultsController;
    

    并在其中添加以下行(在此示例中,我们仅获得托管对象的不同“标题”属性):

    [fetchRequest setReturnsDistinctResults:YES];
    [fetchRequest setResultType:NSDictionaryResultType];
    [fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:@"title"]];
    self.fetchedResultsController.delegate = nil;
    

    您必须注意如何从 NSFetchedResultsController 访问值...例如在

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
    

    使用以下代码访问数据:

    NSDictionary* title = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [title objectForKey:@"title"];
    

    【讨论】:

      【解决方案4】:

      除了Shinoo提供的解决方案之外,请不要忘记设置 NSFetchedResultsController's delegate to nil 以禁用自动更新,这不适用于 NSDictionaryResultType 和不同的值:

      self.fetchedResultsController.delegate = nil; 
      

      【讨论】:

        猜你喜欢
        • 2019-05-29
        • 2011-12-01
        • 1970-01-01
        • 2011-01-27
        • 2022-11-08
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多