NSPredicate包含字符串小写

19

我正在使用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];
}

这是商店实体:

enter image description here

我需要将 name 转换为小写,并查看它是否以小写格式包含在 shopSearchBar.text 中。

例如:

我有这四家商店:

  • Shop1
  • shop 1
  • my shop
  • Shop

如果用户搜索文本为“shop”,则必须返回所有这些商店。

你知道如何做吗?

3个回答

73

这是我解决问题的方法:

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

4
你无需检查 text 是否为 _nil_。只需写 if (shopSearchbar.text.length),它会在 text 为空或为 nil 的情况下返回 _nil_。 - Artem M

2
(a) 你可以在代码库中添加一个列 - lowercaseName - 并且每次保存商店时,保存其名称的小写版本。然后,你的谓词就只需要进行比较即可 :)
(b) 然而,如果你只是想进行大小写不敏感的比较,请尝试这个方法:
if ((shopSearchBar.text != nil) && ([shopSearchBar.text length] > 0))
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE[cd] %@",shopSearchBar.text];
    [fetchRequest setPredicate:predicate];
}

这也是一种不区分音标的比较方法。查看此文档页面中的字符串比较部分以获取更多选项。
(a) 可以提供更快的查询速度,但代码较为复杂。 (b) 可以提供非常简单的保存方法,但查询速度会稍微慢一些。

我不知道我是否做错了什么,但它不起作用。 - VansFannel
1
那你肯定做错了 ;) 你有人们正在进行的搜索和应该匹配的商店的例子吗?你试过用BEGINSWITH代替LIKE吗 - 这可能会有所帮助? - deanWombourne
我在我的问题中添加了一个示例,以展示我想要做什么。 - VansFannel
我猜你可以尝试所有不同的字符串比较谓词方法,直到找到能够实现所需功能的方法,例如LIKE,BEGINSWITH等。祝你好运! - deanWombourne

2

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

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

2
如果基础存储是SQLite,则此项不可用。详情请参阅https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/Reference/NSPredicate.html#//apple_ref/doc/uid/TP30001187-DontLinkElementID_1 - deanWombourne
非常感谢,我已经寻找了很长时间 :) (y) - ishhhh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接