将键作为参数传递给predicateWithFormat中的参数 [英] Pass the key to predicate as parameter in predicateWithFormat

查看:207
本文介绍了将键作为参数传递给predicateWithFormat中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能听起来很愚蠢,但这里是要预测的数据:

This may sounds silly, but here is the data to predicate:

@interface Person

@property NSString *name;
@property NSString *phone;
@property NSString *address;

@end

我有一个NSPredicate将搜索Person Array,按名称搜索。通常情况下,我会使用它像

I got an NSPredicate that will search through Person Array, search by Name. Normally, I will use it like

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];

但是如何使用密钥(名称)作为参数?喜欢

But how can I use the key (name) as a parameter? Like

NSString *key = @"name";
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"%@ contains[c] %@", key, searchText];

谓词1工作正常,但谓词2没有。当我使用lldb调试时,这两个中的不同:

The predicate1 works fine, but the predicate2 doesn't. The different of those 2 when I debug with lldb:

po [predicate1 predicateFormat]
name CONTAINS[c] "Eddie"

po [predicate2 predicateFormat]
"name" CONTAINS[c] "Eddie"

问题是:我可以使谓词2工作吗?我想把密钥传给搜索(名称)作为参数...如果我可以,怎么做?

Question is: Can I make the predicate2 work? I want to pass the key to search (name) as a parameter... If I can, how?

推荐答案

Predicate Programming Guide


当使用%@ 将字符串变量替换为格式字符串时,它们被引号括起来。如果要指定动态属性名称,请使用格式字符串中的%K

When string variables are substituted into a format string using %@ , they are surrounded by quotation marks. If you want to specify a dynamic property name, use %K in the format string

所以你的谓词应该是

NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"%K contains[c] %@", key, searchText];

这篇关于将键作为参数传递给predicateWithFormat中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆