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