iphone - 为什么这个 NSPredicate 不起作用?

标签 iphone objective-c string predicate nspredicate

我有一个非常简单的 NSPredicate:

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"name beginswith '%@'", theString];
[matchingTags filterUsingPredicate:sPredicate];

当 theString == "p"时,这会导致数组有 0 个结果

但是,当我这样做时:

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"name beginswith 'p'"];
[matchingTags filterUsingPredicate:sPredicate];

正如预期的那样,我得到了 100 多个结果。

我已经用 NSLog() 检查了“theString”,它的值是正确的。我觉得我错过了一些重要的 secret 。可能是因为我使用的是字符串而不是字符?

想法?

最佳答案

查看文档 here

If you use variable substitution using %@ (such as firstName like %@), the quotation marks are added for you automatically.

所以基本上,它正在寻找以“p”开头的名称,而不是 p。将代码更改为:

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"name beginswith %@", theString];

应该可以

关于iphone - 为什么这个 NSPredicate 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3134407/

相关文章:

ios - 在 iOS 上的 Swift 中将字节流保存到文件

iphone - 邮件应用程序如何在编辑模式下禁用 UISearchBar?

c - char* 的合法使用

python - 尝试根据列是否包含特定字符串对其进行重新编码

iphone - 重新开始并升级商店中的应用程序(新项目 - CoreData)

iphone - 如何在 Xcode 中以编程方式按下 iOS 小键盘按键?

ios - 根据单独的数组对字典数组进行排序?

iphone - 在 UIAlertView 响应中设置 NSString 的值,不能在其他地方使用吗?

ios - 如何在 iOS 中使用月份和年份比较两个日期

java - Java 中的 str.contains