NSPredicate包含字符串小写

时间:2013-01-30 18:46:33

标签: ios core-data nspredicate

我正在使用iOS SDK 6.0和XCode 4.5.2开发iOS应用程序。我的目标发展是4.3。

我正在使用Core Data来管理我的数据。现在我有NSPredicate来搜索商店:

if ((shopSearchBar.text != nil) && ([shopSearchBar.text length] > 0))
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",shopSearchBar.text];
    [fetchRequest setPredicate:predicate];
}

这是Shop实体:

enter image description here

我必须将名称转换为小写,然后查看它是否包含小写格式的shopSearchBar.text

示例:

我有这四家店铺:

  • Shop1
  • shop 1
  • 我的店铺
  • 商店

如果用户搜索文本是“shop”,则必须返回所有文本。

你知道怎么做吗?

3 个答案:

答案 0 :(得分:61)

这就是我解决问题的方法:

if ((shopSearchBar.text != nil) && ([shopSearchBar.text length] > 0))
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@",
                              shopSearchBar.text];
    [fetchRequest setPredicate:predicate];
}

答案 1 :(得分:3)

您应该能够使用NSPredicat的predicateWithBlock:方法:

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *bind) {
return [self.name compare:shopSearchBar.text options:NSCaseInsensitiveSearch] == NSOrderedSame; }];

答案 2 :(得分:2)

(a)您可以在存储库中添加一个列 - lowercaseName - 每次保存商店时,只保存其名称的小写版本。然后你的谓词只是比较:)

(b)但是,如果你想要的只是做一个不区分大小写的比较,试试这个:

if ((shopSearchBar.text != nil) && ([shopSearchBar.text length] > 0))
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE[cd] %@",shopSearchBar.text];
    [fetchRequest setPredicate:predicate];
}

这也是变音符号不敏感的比较。查看this docs page的字符串比较部分以获取更多选项。

(a)为您提供更快的查询,但代码更复杂。 (b)为您提供非常简单的保存方法,但(稍微)慢一些查询