gpt4 book ai didi

ios - 构建复杂 NSCompoundPredicate 的最佳方法是什么?

转载 作者:技术小花猫 更新时间:2023-10-29 11:04:06 26 4
gpt4 key购买 nike

我需要用很多数据构建一个NSPredicate。例如,在 SQL 中,我会执行如下操作:

SELECT * 
FROM TRANSACTIONS
WHERE CATEGORY IN (categoryList)
AND LOCATION IN (locationList)
AND TYPE IN (typeList)
AND NOTE contains[cd] "some text"
AND DATE >= fromDate
AND DATE <+ toDate

我正在努力解决如何将其构建为 NSPredicate 以便与 Core Data 一起使用的问题。我已经阅读了文档......它只提供了简单的例子。如果有人能给我指出一个更复杂的例子,我将不胜感激。


好吧,两年来我一直在这里找到许多人认为有用的答案。我的帖子被删了。这是包含解决方案的更新 URL。

https://www.radeeccles.com/convert-sql-statement-to-an-nspredicate-for-use-with-core-data/

最佳答案

您需要做的是为每个子句创建一个谓词。例如,让我们分解您的查询:

  1. 从交易中选择 *
  2. 类别在(categoryList)中
  3. 和位置在(locationList)
  4. 然后输入(typeList)
  5. AND NOTE contains[cd] "some text"
  6. AND DATE >= fromDate AND DATE <+ toDate

基于此,您有 5 个谓词 (2-6)。因此,让我们一项一项地研究它们。

 NSPredicate *inCategoryPredicate = [NSPredicate predicateWithFormat:@"Category IN %@", categoryList];

NSPredicate *locationPredicate = [NSPredicate predicateWithFormat:@"Location IN %@", locationList];

NSPredicate *typePredicate = [NSPredicate predicateWithFormat:@"Type IN %@", typeList];

NSPredicate *notePredicate = [NSPredicate predicateWithFormat:@"Note contains[c] %@", @"Some Text"];

NSPredicate *startDatePredicate = [NSPredicate predicateWithFormat:@"Date => @", fromDate];

NSPredicate *endDatePredicate = [NSPredicate predicateWithFormat:@"Date <= @", toDate];

现在您只需要将它们连接到一个谓词中:Apple's documentation states :

You should structure compound predicates to minimize the amount of work done. Regular expression matching in particular is an expensive operation. In a compound predicate, you should therefore perform simple tests before a regular expression;

话虽这么说,但您应该首先从“简单”谓词开始。所以:

NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects: startDatePredicate, endDatePredicate, inCategoryPredicate, locationPredicate, typePredicate, notePredicate];

如果你对它进行 NSLog,你总是可以了解谓词(sql where)是什么样子的。

关于ios - 构建复杂 NSCompoundPredicate 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3955717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com