NSPredicate predicateWithFormat passing in name of attribute

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 14:35:28

问题


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

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