问题
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?
回答1:
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".)
来源:https://stackoverflow.com/questions/14385011/nspredicate-predicatewithformat-passing-in-name-of-attribute