通过以编程方式设置密钥来dynamic创buildNSPredicate

为什么以下的代码片段工作,而不是后者?

片段1

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

片段2

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

我必须根据我的方法中收到的参数dynamic创build谓词。

coin_unique是一个键,所以它需要%K格式说明符:

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

格式语法在这里描述得相当好。

即使我的NSPredicate格式正确,我也得到了以下错误。

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

就像一个傻瓜,我忘了将第二个parameter passing给谓词格式(因为有两个%@ )。 即NSPredicate(format:predicateFormat,argumentArray:[Date()])在数组中只有一个元素时,它需要是两个: [Date(), Date()]