使用预构建字符串创建谓词
有没有办法直接从预先格式化的字符串创建 nspredicate 而无需调用 predicateWithFormat?最终字符串如下所示:
(ineptic=1) AND (dischargedate!=
NSMutableString *preds = [[NSMutableString alloc] initWithString:@""];
NSArray *provs = [self.providerCode componentsSeparatedByString:@"|"];
for (NSString *prov in provs) {
[preds appendFormat:@" (attending=%@) OR (admitting=%@) OR (consulting contains[cd] %@) ", prov, prov, prov];
}
NSString *final = [NSString stringWithFormat:@"(inpatient=%@) AND (dischargedate!=%@) AND (%@)", [NSNumber numberWithBool: self.inpatients], [NSNull null], preds];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:final]];
Is there a way to create an nspredicate directly from a pre-formatted string without calling predicateWithFormat? The final string would look something like:
(inpatient=1) AND (dischargedate!=<null>) AND ((attending=SMITH) OR (admitting=SMITH) OR (consulting contains[cd] SMITH) OR (attending=JONES) OR (admitting=JONES) OR (consulting contains[cd] JONES))
NSMutableString *preds = [[NSMutableString alloc] initWithString:@""];
NSArray *provs = [self.providerCode componentsSeparatedByString:@"|"];
for (NSString *prov in provs) {
[preds appendFormat:@" (attending=%@) OR (admitting=%@) OR (consulting contains[cd] %@) ", prov, prov, prov];
}
NSString *final = [NSString stringWithFormat:@"(inpatient=%@) AND (dischargedate!=%@) AND (%@)", [NSNumber numberWithBool: self.inpatients], [NSNull null], preds];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:final]];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,可以,但是您需要稍微修改格式字符串。
而不是这样做:
您需要这样做:
请注意
%@
修饰符周围使用单引号。这就是谓词如何知道它是一个常量值的方式。然而,即使您走这条路,您仍然会陷入使用
predicateWithFormat:
的困境,而您似乎想避免这种情况。您还可能会遇到如何在格式字符串中使用NSNull
的问题。我建议做类似这样的事情:
这是使用几个不同的巧妙的东西:
@"attending = $prov OR grantting = $prov OR Advisory CONTAINS[cd] $prov"
一次,然后只需用新值替换$prov
每次你有一个不同的提供者Yes you can, but you need to modify the format string slightly.
Instead of doing:
You'd need to do:
Note the use of single-quotes around the
%@
modifier. That's how the predicate knows it's a constant value.However, even if you go this route, you're still stuck using
predicateWithFormat:
, which you appear to want to avoid. You'll also likely have issues with how you're usingNSNull
in the format string.I would recommend doing something more like this:
This is using a couple different neat things:
@"attending = $prov OR admitting = $prov OR consulting CONTAINS[cd] $prov"
once, and then simply substitute in new values for$prov
each time you have a different providerNSCompoundPredicate
to turn multiple predicates into a single, groupedOR
orAND
predicate.