如何在 NSPredicate
中使用多个条件?
我正在使用它,但在返回的数组中没有得到任何东西。
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);
数量和类别有时可以为空。我应该如何构造 NSPredicate
?
最佳答案
您可以使用其他 NSPredicate
对象和 NSCompoundPredicate
类构建您的 placesPredicate
类似的东西:
NSPredicate *p1 = [NSPredicate predicateWithFormat:@"place CONTAINS[cd] %@", placeTextField.text];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"category CONTAINS[cd] %@", selectedCategory];
NSPredicate *p3 = [NSPredicate predicateWithFormat:@"(dates >= %@) AND (dates <= %@)", selectedFromDate,selectedToDate];
NSPredicate *p4 = [NSPredicate predicateWithFormat:@"(amount >= %f) AND (amount <= %f)", [amountFromTextField.text floatValue],[amountToTextField.text floatValue]];
NSPredicate *placesPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[p1, p2, p3, p4]];
现在,如果您缺少类别,例如您可以使用虚拟 YES
谓词来替换它:
NSPredicate *p2;
if (selectedCategory) {
p2 = [NSPredicate predicateWithFormat:@"category CONTAINS[cd] %@", selectedCategory];
} else {
p2 = [NSPredicate predicateWithBool:YES]
}
关于objective-c - NSPredicate 中的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10140376/