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

rad*_*six 10 sql core-data nspredicate ios

我需要构建一个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
Run Code Online (Sandbox Code Playgroud)

我正在努力将其构建NSPredicate为与Core Data一起使用.我已经阅读了文档......它只提供了简单的例子.如果有人能指出一个更复杂的例子,我当然会很感激.


好吧,我在这里得到了两年的答案,很多人都觉得有帮助.我的帖子被删除了.以下是解决方案的更新URL.

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

Are*_*res 9

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

  1. SELECT*FROM TRANSACTIONS
  2. CATEREORY IN(categoryList)
  3. 和位置(locationList)
  4. 和TYPE IN(typeList)
  5. AND NOTE包含[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];
Run Code Online (Sandbox Code Playgroud)

现在你只需将它们加入到一个谓词中:Apple的文档说明:

您应该构造复合谓词以最小化完成的工作量.正则表达式匹配尤其是昂贵的操作.因此,在复合谓词中,您应该在正则表达式之前执行简单测试;

这就是说,你应该首先从"简单"谓词开始.所以:

NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects: startDatePredicate, endDatePredicate, inCategoryPredicate, locationPredicate, typePredicate, notePredicate];
Run Code Online (Sandbox Code Playgroud)

如果您使用NSLog,您始终可以了解谓词(sql where)的样子.