NSPredicate 无法解析格式字符串

NSPredicate unable to parse format string

我看不出这行代码有什么问题。为什么不能解析?

[NSPredicate predicateWithFormat:@"(username  CONTAINS[cd] %1$@) || "
                                  "(userId    CONTAINS[cd] %1$@) || "
                                  "(firstname CONTAINS[cd] %1$@) || "
                                  "(lastname  CONTAINS[cd] %1$@)", searchString]"

日志也无济于事。

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(username CONTAINS[cd] %1$@) || (userId CONTAINS[cd] %1$@) || (firstname CONTAINS[cd] %1$@) || (lastname CONTAINS[cd] %1$@)"'

编辑 1:

好的,predicateWithFormat 似乎不理解“%1$@”。我将其切换为

[... predicateWithFormat:[NSString stringWithFormat:...]] // (same format as above)

过线了。但是,下一个问题是:

self.filteredUserList = [self.userList filteredArrayUsingPredicate:predicate];

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: the entity User is not key value coding-compliant for the key "a".'

"a"是我在searchTextBox中输入的关键字。 WUT?

我在调试控制台打印出谓词,看起来没有问题:

username CONTAINS[cd] a OR userId CONTAINS[cd] a OR firstname CONTAINS[cd] a OR lastname CONTAINS[cd] a

编辑 2:

好的,这个超级难看的代码解决了问题:

[NSPredicate predicateWithFormat:@"(username  CONTAINS[cd] %@) || "
                                  "(userId    CONTAINS[cd] %@) || "
                                  "(firstname CONTAINS[cd] %@) || "
                                  "(lastname  CONTAINS[cd] %@)", searchString, searchString, searchString, searchString];

如果我以后想扩大搜索范围怎么办?我必须添加更多参数?更多 ", searchString, searchString, searchString"?

已解决

感谢 Ewan 和 Bannings,为我的问题提供了 2 个选项。我测试了他们两个,他们很有魅力。谁能解释一下这两者之间的区别,在什么情况下我应该使用哪个选项?

** 注意 **

Bannings 的回答还不错,直到我的搜索字符串包含单引号 ',然后应用程序崩溃了。所以我觉得用Ewan的那个比较好。

您需要为每个变量添加字符串,如果您使用 5 %@,您需要应用相同的 searchString 值或另一个填充该 %@ 的值

[NSPredicate predicateWithFormat:@"(username CONTAINS[cd] %1$@) ||
(userId CONTAINS[cd] %1$@) || (firstname CONTAINS[cd] %1$@) ||
(lastname CONTAINS[cd] %1$@)", searchString1,searchString2,searchString3,searchString4]

你可以这样做:

[[NSPredicate predicateWithFormat:@"(username CONTAINS[cd] $str) || ..."] predicateWithSubstitutionVariables:@{@"str": searchString}];

尝试将 %1$@ 更改为 '%1$@':

NSString *formatString = [NSString stringWithFormat:@"(username CONTAINS[cd] '%1$@') || (userId CONTAINS[cd] '%1$@') || (firstname CONTAINS[cd] '%1$@') || (lastname CONTAINS[cd] '%1$@')", searchString];
NSPredicate *predicate = [NSPredicate predicateWithFormat:formatString];