1

是否可以将保留字,特别是ORand替换AND为 a predicateFormat

我试过了:

NSString *andOr = (isAnd ? @"AND" : @"OR");  // isAnd is a BOOL variable
NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"firstName == %@ %K lastName == %@",
                          user.firstName, andOr, user.lastName];

但我得到了:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Unable to parse the format string "firstName == %@ %K lastName == %@"

我试过%s(也%S)而不是%K但得到了同样的例外。

我现在的工作解决方案是predicateFormat单独创建。

NSString *predicateFormat = [NSString stringWithFormat:
                             @"firstName == %%@ %@ lastName == %%@", andOr]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat,
                          user.firstName, user.lastName];

但是,我想知道这是否可以在不predicateFormat单独创建的情况下完成。

4

2 回答 2

1

是的,它可以:

NSPredicate *firstName = [NSPredicate predicateWithFormat:@"firstName == %@", [user firstName]];
NSPredicate *lastName = [NSPredicate predicateWithFormat:@"lastName == %@", [user lastName]];
NSArray *subpredicates = [NSArray arrayWithObjects:firstName, lastName, nil];

NSPredicate *predicate = nil;
if (isAnd) {
  predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
} else {
  predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
}
于 2011-12-26T20:32:10.997 回答
0

使用搜索栏文本我正在过滤数据。

下面的代码很简单,不需要任何解释

NSString *predFormat=[NSString stringWithFormat:@"FirstName CONTAINS[c] '%@' OR LastName CONTAINS[c] '%@' OR Phone CONTAINS[c] '%@'",searchValue,searchValue,searchValue]; //喜欢

NSPredicate *predicate = [NSPredicate predicateWithFormat:predFormat];

NSArray *tempData = [数组过滤数组UsingPredicate:谓词];

希望这对你有用..快乐编码....

于 2013-07-25T10:07:05.777 回答