NSPredicate - 无法解析格式字符串

Sat*_*ran 20 core-data nspredicate ios

我正在尝试NSPredicate使用此字符串" 193e00a75148b4006a451452c618ccec" 来编写带有my_column值的行来获取行,并且我得到了下面的崩溃.

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无法解析格式字符串"my_column = 193e00a75148b4006a451452c618ccec"'

我的谓词陈述

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==\"%@\"",attributeName,itemValue]];
Run Code Online (Sandbox Code Playgroud)

也尝试了这个

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@",attributeName,itemValue]];
Run Code Online (Sandbox Code Playgroud)

这个

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = %@",attributeName,itemValue]];
Run Code Online (Sandbox Code Playgroud)

还有这个

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@=\"%@\"",attributeName,itemValue]];
Run Code Online (Sandbox Code Playgroud)

请帮忙.

当我尝试使用Martin R的答案时,我发现了这一点

fetchRequest.predicate=[NSPredicate predicateWithFormat:@"%@==%@",attributeName,itemValue];
Run Code Online (Sandbox Code Playgroud)

attributeName我传递带有''所以我取下了attributeName并硬编码了它,然后它工作正常.

Mar*_*n R 45

将字符串括在单引号中:

[NSPredicate predicateWithFormat:@"my_column = '193e00a75148b4006a451452c618ccec'"]
Run Code Online (Sandbox Code Playgroud)

或者更好,使用参数替换:

[NSPredicate predicateWithFormat:@"my_column = %@", @"193e00a75148b4006a451452c618ccec"]
Run Code Online (Sandbox Code Playgroud)

如果搜索字符串包含特殊字符(如'或),则第二种方法可以避免问题".

备注:stringWithFormat在构建谓词时不要使用.stringWithFormat并且 predicateWithFormat处理%K%@格式不同,因此组合这两种方法非常容易出错(并且不必要).

  • @satheeshwaran:在构建谓词时永远不要使用`stringWithFormat`!请完全按照我在答案中所写的那样尝试. (2认同)