【问题标题】:Using NSPredicate to determine if a string equals another string使用 NSPredicate 判断一个字符串是否等于另一个字符串
【发布时间】:2011-02-27 09:15:48
【问题描述】:

我有一个 NSArray 的 CalEvents 使用 [CalCalendarStore eventPredicateWithStartDate] 方法返回。从返回的事件中,我试图只保留事件标题 == @"on call"(不区分大小写)的那些。

我可以将标题包含 @"on call" 的事件保留在数组中,代码如下(其中“事件”是填充有CalEvents 的“NSArray”):

NSPredicate *onCallPredicate = [NSPredicate predicateWithFormat:@"(SELF.title CONTAINS[c] 'on call')"];
[events filteredArrayUsingPredicate:onCallPredicate];

我尝试过使用谓词格式字符串,例如:

@"SELF.title == 'on call'" 但这似乎不起作用。

有更简单的方法吗?

【问题讨论】:

    标签: objective-c nsstring nsarray nspredicate


    【解决方案1】:

    试试[NSPredicate predicateWithFormat:@"title ==[c] 'on call'"];

    [c] 使相等比较不区分大小写。)

    【讨论】:

    • +1,尽管您可以在 == 之后添加 [c] 修饰符以使其不区分大小写。
    • 将其编辑为不区分大小写。
    • 只是好奇,如果不使用任何 (*?.) 通配符,MATCH[n] 是否适用于 ==?
    【解决方案2】:

    尝试使用@"self.title like[c] 'on call'" 格式的谓词。以下示例代码输出 2 个字符串:

    NSArray* ar = [NSArray arrayWithObjects:@"on call", @"I'm on call", @"lala", @"On call", nil];
    NSArray* filt = [ar filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self like[c] 'on call'"]];
    NSLog([filt description]);
    
    //Output
    "on call",
    "On call"
    

    【讨论】:

    • 使用==like进行字符串比较有区别吗?
    • 在您的情况下看起来他们的工作相同。但是,如果您想在字符串比较中使用通配符,那么 '==' 将不起作用,您需要改用 LIKE。
    猜你喜欢
    • 2013-03-11
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 2011-02-19
    相关资源
    最近更新 更多