Multiple conditions in NSPredicate
cocoa-touch, ios, ipad, nspredicate, objective-c
Solution
I would tend to handle this one piecemeal. That is,
placePredicate = [NSPredicate predicateWithFormat:@"place CONTAINS[cd] %@",placeTextField.text];
NSMutableArray *compoundPredicateArray = [ NSMutableArray arrayWithObject: placePredicate ];
if( selectedCategory != nil ) // or however you need to test for an empty category
{
categoryPredicate = [NSPredicate predicateWithFormat:@"category CONTAINS[cd] %@",selectedCategory];
[ compoundPredicateArray addObject: categoryPredicate ];
}
// and similarly for the other elements.
Note that I don't bother even putting into the array the predicate for category (or anything else) when I know there isn't one.
// Then
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:
compoundPredicateArray ];
And if I were planning to do it a lot, I wouldn't use the format method, but keep around the building blocks and just change whatever changes between uses.
Problem
How to use multiple conditions with `NSPredicate`? I am using this but not getting anything in the returned array . ``` NSPredicate *placePredicate = [NSPredicate predicateWithFormat:@"place CONTAINS[cd] %@ AND category CONTAINS[cd] %@ AND ((dates >= %@) AND (dates <= %@)) AND ((amount >= %f) AND (amount <= %f))",placeTextField.text,selectedCategory,selectedFromDate,selectedToDate,[amountFromTextField.text floatValue],[amountToTextField.text floatValue]]; NSArray *placePredicateArray = [dataArray filteredArrayUsingPredicate:placePredicate]; NSLog(@"placePredicateArray %@", placePredicateArray); ``` The amount and the category can be empty sometimes. How should I construct the `NSPredicate`?