【问题标题】:NSPredicate that is the equivalent of SQL's LIKENSPredicate 相当于 SQL 的 LIKE
【发布时间】:2011-02-14 00:26:06
【问题描述】:

我正在寻找一种使用NSPredicate 设置LIKE 条件来获取对象的方法。除此之外,OR 也很有用。我正在尝试做一些事情,如果用户搜索“James”,我可以写一个NSPredicate,它相当于:

select * from users where firstname LIKE '%James%' OR lastname LIKE '%James%';

【问题讨论】:

    标签: iphone cocoa cocoa-touch core-data nspredicate


    【解决方案1】:

    CONTAINS 运算符肯定可以正常工作。如果您正在寻找更直接的关联,那么您还可以使用 LIKE 运算符(* = 0 个或更多字符,? = 1 个字符):

    NSString *_mySearchKey = @"James";
    NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"firstname LIKE '*%1$@*' OR lastname LIKE '*%1$@*'", _mySearchKey];
    

    供参考:
    https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-215868

    【讨论】:

    • 我知道那是很久以前的事了,但这不起作用,因为 NSPredicate 不会替换引用的内容 '%@' 将保持 '%@'...
    • beginswith[c] 为我做了,但仍然有人设法生成动态 LIKE 查询,例如 '%@*'
    • 使用like 的技巧是在参数中包含* 标记。即:NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K LIKE[cd] %@", kMDItemDisplayName, [NSString stringWithFormat:@"*%@*", appname]];
    • 1$@ 是做什么的?
    • @shim 专门标识第一个参数。对比一下,如果作者刚刚使用了两次%@;在这种情况下,他需要提供两次_mySearchKey。例如。 NSLog(@"%1$@ %1$@", @"Hat"); 将输出“Hat Hat”。
    【解决方案2】:

    另一种可能性

    @"firstname beginswith[c] James"
    

    作为 contains 的一个不错的替代品

    有时包含并不总是正确的答案

    【讨论】:

    • 不匹配 "SuperJames" :) beginwith is not equal to sql's like '%foo%'
    【解决方案3】:
    NSString *_mySearchKey = @"James";
    NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"(firstname CONTAINS[cd] %@) OR (lastname CONTAINS[cd] %@)", _mySearchKey, _mySearchKey];
    

    【讨论】:

    • 找到了!这意味着不区分大小写和变音符号
    • @AlexReynolds 你为什么不使用 LIKE ?
    • 一个更好的问题是:为什么我应该使用 LIKE?
    • 这不适用于空字符串@""。有什么建议? [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", strFilter] 当 strFilter 为 @"" 时不起作用
    • 在运行谓词测试之前检查字符串是否为空,并单独处理这种情况。 stackoverflow.com/questions/899209/…
    猜你喜欢
    • 2011-10-13
    • 2011-07-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多