+[NSPredicate predicateWithFormat] 替换保留字
是否可以将保留字(特别是 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
的情况下完成此操作。
Is it possible to substitute reserved words, specifically OR
and AND
, into a predicateFormat
?
I tried:
NSString *andOr = (isAnd ? @"AND" : @"OR"); // isAnd is a BOOL variable
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"firstName == %@ %K lastName == %@",
user.firstName, andOr, user.lastName];
But I got:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Unable to parse the format string "firstName == %@ %K lastName == %@"
I tried %s
(and also %S
) instead of %K
but got the same exception.
My working solution for now is to create the predicateFormat
separately.
NSString *predicateFormat = [NSString stringWithFormat:
@"firstName == %%@ %@ lastName == %%@", andOr];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat,
user.firstName, user.lastName];
But, I was wondering if this could be done without creating predicateFormat
separately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,它可以:
Yep, it can:
使用搜索栏文本我正在过滤数据。
下面的代码很简单,不需要任何解释
NSString *predFormat=[NSString stringWithFormat:@"FirstName CONTAINS[c] '%@' OR LastName CONTAINS[c] '%@' OR Phone CONTAINS[c] '%@'" ,搜索值,搜索值,搜索值]; //LIKE
NSPredicate *predicate = [NSPredicate predicateWithFormat:predFormat];
NSArray *tempData = [数组filteredArrayUsingPredicate:谓词];
希望这对你有用..
快乐编码....
Using search bar text i am filtering the data.
Below code is simple and no need of any explanation
NSString *predFormat=[NSString stringWithFormat:@"FirstName CONTAINS[c] '%@' OR LastName CONTAINS[c] '%@' OR Phone CONTAINS[c] '%@'",searchValue,searchValue,searchValue]; //LIKE
NSPredicate *predicate = [NSPredicate predicateWithFormat:predFormat];
NSArray *tempData = [array filteredArrayUsingPredicate:predicate];
Hope this will work for you..
Happy coding....