What is the best way to build a complex NSCompoundPredicate?

老子叫甜甜 提交于 2019-12-03 02:52:14

What you need to do is to create a Predicate for each one of your clauses. For example let's break down your query:

  1. SELECT * FROM TRANSACTIONS
  2. WHERE CATEGORY IN (categoryList)
  3. AND LOCATION IN (locationList)
  4. AND TYPE IN (typeList)
  5. AND NOTE contains[cd] "some text"
  6. AND DATE >= fromDate AND DATE <+ toDate

Based on this, you have 5 predicates (2-6). So let's work on them one by one.

 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];

Now you just need to join them into just one predicate: 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;

This being said then you should start with the "easy" predicates first. So:

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

You can always get an idea of what the predicate (sql where) looks like if you NSLog it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!