NSPredicate format string doesn't work

怎甘沉沦 提交于 2019-12-22 10:14:08

问题


In my code, I want to check and see if a record already exists, so I know whether to create it or update it. But I ran into a problem. The problem is when I use this:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"%@ == %@", ATTRIBUTE_ID, idNumber];
[request setPredicate:pred];

This doesn't work. It always claims no results were found. However, it works just fine when I rewrite it like so:

NSExpression *lhs = [NSExpression expressionForKeyPath:ATTRIBUTE_ID];
NSExpression *rhs = [NSExpression expressionForConstantValue:idNumber];
NSPredicate *pred = [NSComparisonPredicate
                                     predicateWithLeftExpression:lhs
                                     rightExpression:rhs
                                     modifier:NSDirectPredicateModifier
                                     type:NSEqualToPredicateOperatorType
                                     options:0];
[request setPredicate:pred];

What am I missing or doing incorrectly in the format string?


回答1:


Your ATTRIBUTE_ID is a key, so you should use %K in the format string for that part of it.

The format string would look like this (upper case K as pointed out in the comments):

[NSPredicate predicateWithFormat:@"%K == %@", ATTRIBUTE_ID, idNumber];


来源:https://stackoverflow.com/questions/12413929/nspredicate-format-string-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!