从字符串创建 NSPredicate
我需要从多个值数组形成一个谓词。所以我想我可以首先形成一个包含所有值的字符串,然后传递该字符串以在谓词中使用,即
NSString* stringForPredicate = [[NSString alloc] init];
if (fromDate != nil) {
stringForPredicate = [stringForPredicate stringByAppendingFormat:@"(Date > %@ AND Date < %@)", fromDate, toDate];
}
我需要进行进一步的计算来形成最终的谓词字符串。
现在,我希望谓词使用这个字符串。我认为这样的东西会起作用:
NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:@"%@",stringForPredicate];
但它不会并抛出异常:
“无法解析格式字符串“%@””
有没有办法让这个工作起作用?
谢谢,
I need to form a predicate from multiple arrays of values. So I thought I can initially form a string with all the values, and then pass that string for usage in a predicate, i.e
NSString* stringForPredicate = [[NSString alloc] init];
if (fromDate != nil) {
stringForPredicate = [stringForPredicate stringByAppendingFormat:@"(Date > %@ AND Date < %@)", fromDate, toDate];
}
There are further calculations that I do to form the final predicate string.
Now, I want the predicate to use this string. I thought that something like this would work:
NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:@"%@",stringForPredicate];
But it doesnt and throws the exception:
'Unable to parse the format string "%@"'
Is there a way I can make this work?
thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
stringForPredicate 变量实际上包含format_string。因此,您需要分配该变量来代替 format_string,并在其后传递 args,用逗号分隔,如下所示。
对于复合谓词:
The stringForPredicate variable actually contains the format_string. So, you need to assign that variable in place of the format_string, and pass the args after that, seperated by commas, like this.
For compound predicates:
这个不行吗?
或者您必须
从 参考文档
试试这个
Wont this do it?
or you have to do this
From the reference documents
Try this
对于那些使用 swift 的人:
For those using swift: