objective-c - 列名的 NSPredicate 问题

标签 objective-c core-data

我正在尝试使用 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/

相关文章:

ios - Xcode:表达式不可分配

Swift:核心数据 - 解决对象创建的逻辑问题

ios - 在核心数据项目中导入数据和修改实体

iphone - 改变色彩空间和图像

iphone - AVCaptureSession 前置摄像头方向

iphone - init中使用loadNibNamed时,ViewController收不到viewDidLoad事件

iphone - Xcode 4 : nib files not loading when run

ios - 我应该如何命名可导入的 .sqlite 持久存储?

ios - 解析数据并将其插入 SQLITE - ios

core-data - 使用带有根 UITabBarController 的 Storyboard传递 ManagedObjectContext 以查看 Controller