Creating NSPredicate dynamically by setting the key programmatically

旧城冷巷雨未停 提交于 2019-12-03 12:47:34

问题


Why does the former of following snippets work while not the latter ?

Snippet 1

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(coin_unique == %@)", [NSNumber numberWithInt:species]];

Snippet 2

// Does NOT Work
NSString *predicateText = @"coin_unique";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ == %@)", predicateText, [NSNumber numberWithInt:species]];

I have to dynamically create predicate depending upon the argument received in my method.


回答1:


coin_unique is a key, so it needs the %K format specifier:

NSString *predicateText = @"coin_unique";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", predicateText, [NSNumber numberWithInt:species]];

The format syntax is described quite well here.




回答2:


I got the following error even though my NSPredicate was formatted correctly.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Insufficient arguments for conversion characters specified in format string.' site:stackoverflow.com

Like a fool I forgot to pass a second argument to the predicate format (because there were two %@). I.e. NSPredicate(format:predicateFormat,argumentArray:[Date()]) has only one element in the array when it needs to be two: [Date(), Date()]



来源:https://stackoverflow.com/questions/15505208/creating-nspredicate-dynamically-by-setting-the-key-programmatically

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