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

标签 ios cocoa nspredicate

这听起来可能很傻,但这里是要断言的数据:

@interface Person

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

@end

我有一个 NSPredicate 可以搜索 Person 数组,按名字搜索。通常,我会像这样使用它

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

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

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

predicate1 工作正常,但 predicate2 不行。当我使用 lldb 调试时,这两个的不同之处:

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

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

问题是:我可以让 predicate2 工作吗?我想将 key 作为参数传递给搜索(名称)...如果可以,如何传递?

最佳答案

来自Predicate Programming Guide

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];

关于ios - 将键作为 predicateWithFormat 中的参数传递给 predicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19673849/

相关文章:

ios - AVPlayerLayer 在 AVPlayer.replaceCurrentItem 上闪烁黑色(带有 :)

iphone - iOS 应用程序和 Windows 身份验证

objective-c - 是否可以调用 NSDictionary 的 valueForKeyPath : when a key contains periods?

swift - 在 swift 3 中创建复杂的 NSCompoundPredicate

ios - 在巨大的 UICollectionView 中加载图片

javascript - 使用 jQuery animate 和scrollTop() 时 iPad 快速触摸的问题

cocoa - 带图层的 NSView 绘制在所有内容上

javascript - 绕过WebView跨域安全

ios - NSManagedObject 类关系中的 NSPredicate 键

syntax - "cdl"在 TOKENMATCHES[cdl] 中有什么作用?