Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate predicateWithFormat passing in name of attribute

Simple question regarding NSPredicate's. I'm trying to construct my predicate with "passed in" values like so :

NSPredicate* currentPredicate = [NSPredicate predicateWithFormat:@"%@ == %@",key,[changesDict valueForKey:@"Id"] ];

However, I haven't been able to get this to work correctly. If I insert the actual value I pass through it does work though. So this works :

NSPredicate* currentPredicate = [NSPredicate predicateWithFormat:@"contactId == %@",[changesDict valueForKey:@"Id"] ];

(Notice i inserted contactId as opposed to the previous example where I pass a string by the same name)

To troubleshoot I NSLogged the two predicates looking at their descriptions and they were different. I'll show them below.

This is the working one

2013-01-17 10:29:25.513 TestingCoreData[1776:3b03] contactId == "5878"

This is the non working one

2013-01-17 10:29:25.513 TestingCoreData[1776:3b03] "contactId" == "5878"

So I can kind of see that it's inserting a string where I really just want the name of the attribute that i'll later be using in the fetch request. But is there any way to accomplish this by passing in values?

like image 853
hatunike Avatar asked Jan 17 '13 17:01

hatunike


1 Answers

For keys or key paths, you have to use the %K format:

[NSPredicate predicateWithFormat:@"%K == %@", key, [changesDict valueForKey:@"Id"]];

(See Parser Basics in the "Predicate Programming Guide".)

like image 57
Martin R Avatar answered Oct 20 '22 02:10

Martin R