NSPredicate中的多个条件

Pre*_*van 13 cocoa-touch objective-c nspredicate ipad ios

如何使用多个条件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);
Run Code Online (Sandbox Code Playgroud)

金额和类别有时可能为空.我应该如何构建NSPredicate

dea*_*rne 30

您可以placesPredicate使用其他NSPredicate对象和NSCompoundPredicate类构建您的

就像是 :

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]];
Run Code Online (Sandbox Code Playgroud)

现在,如果您缺少类别,例如您可以使用虚拟YES谓词来替换它:

NSPredicate *p2;
if (selectedCategory) {
    p2 = [NSPredicate predicateWithFormat:@"category CONTAINS[cd] %@", selectedCategory];
} else {
    p2 = [NSPredicate predicateWithBool:YES]
}
Run Code Online (Sandbox Code Playgroud)


DRV*_*Vic 13

我倾向于处理这一个零碎的事情.那是,

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.  
Run Code Online (Sandbox Code Playgroud)

请注意,当我知道没有类别的谓词时,我甚至不打算将类别的谓词(或其他任何内容)放入数组中.

// Then
    NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:
                                  compoundPredicateArray ];
Run Code Online (Sandbox Code Playgroud)

如果我打算做很多事情,我不会使用格式方法,而是保留构建块,只需更改使用之间的任何变化.