2013-03-19 66 views
8

为什么前面的代码片段不工作而后者工作?通过以编程方式设置密钥来动态创建NSPredicate

片段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]]; 

我必须动态地创建,这取决于参数的谓词在我的方法接收。

回答

18

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

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

格式语法描述相当不错here

0

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

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

我真傻,忘了传递第二个参数谓词格式(因为有两个%@)。即NSPredicate(format:predicateFormat,argumentArray:[Date()])在阵列中只有一个元素时,它需要为两个:[Date(), Date()]

相关问题