【问题标题】:NSPredicate contains string lowercaseNSPredicate 包含字符串小写
【发布时间】:2013-01-14 16:59:32
【问题描述】:

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

这是商店实体:

我必须将 name 转换为小写,看看它是否包含小写格式的shopSearchBar.text

例子:

我有这四家店:

  • 商店1
  • 1号店
  • 我的店铺
  • 商店

如果用户搜索文本为“shop”,则必须全部返回。

你知道怎么做吗?

【问题讨论】:

    标签: ios core-data nspredicate


    【解决方案1】:

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

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

    【讨论】:

    • 您不需要检查text 是否有nil。只写if (shopSearchbar.text.length),它会在两种情况下返回 nil 文本是 nil 或空字符串。
    【解决方案2】:

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

    (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) 为您提供非常简单的保存方法,但(稍微)较慢的查询

    【讨论】:

    • 我不知道是不是我做错了什么,但它不起作用。
    • 那么您做错了什么;) 您是否有一个搜索示例,说明某人正在执行的搜索以及它应该匹配的 Shop?您是否尝试过 BEGINSWITH 而不是 LIKE - 它可能会有所帮助?
    • 我在我的问题中添加了一个示例来说明我想要做什么。
    • 我想尝试所有不同的字符串比较谓词方法,直到找到能够做到这一点的方法,即 LIKE、BEGINSWITH 等。祝你好运!
    【解决方案3】:

    你应该可以使用 NSPredicat 的 predicateWithBlock: 方法:

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

    【讨论】:

    猜你喜欢
    • 2012-09-14
    • 2013-02-02
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多