Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate format string doesn't work

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?

like image 462
Chad Schultz Avatar asked Jul 22 '26 08:07

Chad Schultz


1 Answers

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];
like image 172
Monolo Avatar answered Jul 25 '26 07:07

Monolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!