【问题标题】:how to create compoundpredicate within nsFetchRequest that filters by two parameters of different entity如何在 nsFetchRequest 中创建通过不同实体的两个参数过滤的复合谓词
【发布时间】:2014-06-28 04:26:50
【问题描述】:

关于我的数据模型的一些背景信息:

manufacturer <-->> item <<-->> tag

我目前通过 fetchrequest 生成项目列表:

- (NSFetchRequest*) rankingRequestForItem:(Item*)item {
    NSFetchRequest* r = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
    NSPredicate* p = [NSPredicate predicateWithFormat:@"SELF != %@",item.objectID];
    r.resultType = NSDictionaryResultType;
r.resultType = NSDictionaryResultType;

    r.propertiesToFetch = @[[self objectIDExpressionDescription],@"itemName",
                            [self rankingExpressionDescriptionForTags:[item mutableSetValueForKey:@"itemToTag"]]];

    r.predicate = p;
    r.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"itemName" ascending:YES]];

    return r;
}

这会生成所有项目的列表。我想过滤与特定制造商有关系的项目。所以我在所有项目的列表之后添加了一个谓词,它按 selectedManufacturer 排序。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemToMa = %@", selectedManufacturer];

这可行,但会抓取很多将被过滤掉的项目。对于大型数据集,我假设它会变得越来越慢,因为它会搜索所有项目,而不仅仅是与一个制造商相关的项目。我想过滤初始“rankingRequestForItem”方法中的项目。

是否可以将上面的谓词与顶部谓词一起移动并创建一个复合谓词?

【问题讨论】:

  • [NSPredicate predicateWithFormat:@"SELF != %@ AND itemToMa = %@",item.objectID,selectedManufacturer]
  • 我再次尝试让这变得比它需要的更复杂,感谢 Dan 提供的简单有效的解决方案。

标签: core-data filter fetch predicate nscompoundpredicate


【解决方案1】:

我不会担心性能。 Core Data 在后台管理得很好。有时谓词的顺序很重要,所以也许把制造商过滤器放在第一位。

您可以按照问题评论中的建议将谓词合二为一,或者使用复合谓词——结果几乎相同。

【讨论】:

    猜你喜欢
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2022-01-09
    • 1970-01-01
    • 2013-08-09
    • 2017-04-16
    • 2011-04-30
    相关资源
    最近更新 更多