问题
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