将键作为参数传递给predicateWithFormat中的参数

Edd*_*die 4 cocoa nspredicate ios

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

@interface Person

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

@end
Run Code Online (Sandbox Code Playgroud)

我有一个NSPredicate将搜索Person Array,按名称搜索.通常,我会像使用它一样

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
Run Code Online (Sandbox Code Playgroud)

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

NSString *key = @"name";
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"%@ contains[c] %@", key, searchText];
Run Code Online (Sandbox Code Playgroud)

谓词1工作正常,但谓词2没有.当我用lldb调试时,那两个不同:

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

po [predicate2 predicateFormat]
"name" CONTAINS[c] "Eddie"
Run Code Online (Sandbox Code Playgroud)

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

Gab*_*lla 13

来自谓词编程指南

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

所以你的谓词应该是

NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"%K contains[c] %@", key, searchText];
Run Code Online (Sandbox Code Playgroud)