ios – 构建复杂的NSCompoundPredicate最好的方法是什么?

前端之家收集整理的这篇文章主要介绍了ios – 构建复杂的NSCompoundPredicate最好的方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要用许多数据构建一个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/

解决方法

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

> SELECT * FROM TRANSACTIONS
> WHERE CATEGORY IN(categoryList)
> AND LOCATION IN(locationList)
> AND TYPE IN(typeList)
> AND NOTE包含[cd]“一些文本”
> 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

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)会是什么样子.

原文链接:https://www.f2er.com/iOS/330038.html

猜你在找的iOS相关文章