是否可以将保留字(特别是OR
和AND
)替换为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
的情况下完成此操作。
答案 0 :(得分: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];
}
答案 1 :(得分:0)
使用搜索栏文字我正在过滤数据。
下面的代码很简单,无需任何解释
NSString * predFormat = [NSString stringWithFormat:@“FirstName CONTAINS [c]'%@'或LastName CONTAINS [c]'%@'OR Phone CONTAINS [c]'%@'”,searchValue,searchValue,searchValue] ; // LIKE
NSPredicate * predicate = [NSPredicate predicateWithFormat:predFormat];
NSArray * tempData = [array filteredArrayUsingPredicate:predicate];
希望这对你有用.. 快乐的编码....