我正在尝试使用 NSPredicate 查询表。这基本上是我正在做的事情:
NSNumber *value = [NSNumber numberWithInteger: 2];
NSString *columnName = @"something_id";
NSLog(@"%@ == %@", columnName, value);
NSPredicate *refQuery = [NSPredicate predicateWithFormat: @"%@ == %@", columnName, value];
NSLog 打印出我所期望的(“something_id == 2”),但谓词不起作用。 但是,如果我将谓词更改为:
NSPredicate *refQuery = [NSPredicate predicateWithFormat: @"something_id == %@", value];
那么为什么这行不通,我该如何解决呢?
最佳答案
The Predicate Programming Guide from Apple说:
%@ is a var arg substitution for an object value—often a string, number, or date.
%K is a var arg substitution for a key path.
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.
因此,在您的情况下,您需要将 %K 作为 columnName 的键路径,而不是 %@,后者将添加引号:
NSPredicate *refQuery = [NSPredicate predicateWithFormat: @"%K == %@", columnName, value];
希望这能消除您的疑虑。
关于objective-c - 列名的 NSPredicate 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3942065/