objective-c - NSPredicate 中的多个条件

标签 objective-c ios cocoa-touch ipad nspredicate

如何在 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/

相关文章:

ios - 如何在 Xcode 11 上运行不同版本的 iOS 模拟器?

iphone - layoutSubviews 究竟什么时候被自定义 UITableViewCell 调用?

objective-c - NSArray 上的 'void' 是什么?

ios - WKWebView ScrollView 委托(delegate)

iphone - 根据道路计算两个位置之间的距离

ios - 以编程方式添加约束

cocoa-touch - 如何获取两个日期之间的差异?

iphone - 如何在调用 objective-c 方法之前设置NSString

ios - saveEventually - 在使用 Parse 最小化应用程序时保存

ios - WKWebView 使用 Swift 4 捕获 HTTP 错误代码