为什么前者可以工作,而后者不行?
片段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]];
我必须根据在我的方法中收到的参数动态创建谓词。
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
我像个傻瓜一样忘记给谓词格式传递第二个参数(因为有两个%@
)。例如,NSPredicate(format:predicateFormat,argumentArray:[Date()])
在数组中只有一个元素,而它需要两个元素:[Date(), Date()]