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

2024-05-02

我需要建立一个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与核心数据一起使用。我已阅读文档...它只提供了简单的示例。如果有人能给我指出一个更复杂的例子,我一定会很感激。


嗯,我在这里找到了两年的答案,很多人都认为它很有帮助。我的帖子被删除了。这是包含解决方案的更新后的 URL。

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


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

  1. 从交易中选择 *
  2. 类别在何处(类别列表)
  3. 和位置(位置列表)
  4. 并输入(类型列表)
  5. AND 注意包含[cd]“一些文字”
  6. AND 日期 >= fromDate AND 日期

基于此,您有 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];

现在您只需将它们加入到一个谓词中即可:苹果的文档指出 https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html:

您应该构建复合谓词以尽量减少 完工。正则表达式匹配尤其昂贵 手术。因此,在复合谓词中,您应该执行 正则表达式之前的简单测试;

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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

构建复杂 NSCompoundPredicate 的最佳方法是什么? 的相关文章

随机推荐