【问题标题】:What is the best way to build a complex NSCompoundPredicate?构建复杂的 NSCompoundPredicate 的最佳方法是什么?
【发布时间】:2011-04-26 17:22:45
【问题描述】:

我需要用许多数据构建一个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/

【问题讨论】:

  • 您是否尝试在谓词中输入您的 where 子句。它有一种非常强大的从字符串构建的方法。
  • 我不知道有什么地方可以让我指定生成谓词的 SQL 语句。请指教。
  • 我不知道为什么我的帖子总是被删除。这篇文章帮助了很多人radeeccles.com/…

标签: ios sql core-data nspredicate


【解决方案1】:

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

  1. 从交易中选择 *
  2. 类别在哪里(类别列表)
  3. 和位置在 (locationList)
  4. AND 类型输入 (typeList)
  5. AND NOTE 包含[cd]“一些文本”
  6. AND DATE >= fromDate AND DATE

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

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

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

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

如果您对谓词(sql where)进行 NSLog 记录,您总能了解它的样子。

【讨论】:

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