对象 - 如何检查NSString是否包含一个或另一个?

时间:2017-09-14 02:38:05

标签: objective-c nspredicate

我想检查我的NSString'名称'是否包含“Brittany”或“Bob”,但是下面的代码似乎没有做到这一点?

ViewController.m

NSPredicate *p = [NSPredicate predicateWithFormat:@"name contains[cd] %@ OR name contains[cd] %@", @"Brittany", @"Bob"];
NSArray *filtered = [self.messages filteredArrayUsingPredicate:p];

知道这应该是什么样的吗?我似乎无法正确使用语法。问题是'filtered'不返回包含“Bob”的字符串名称的数组,只是名称中包含“Brittany”的数组。

以下是self.messages包含的内容:

 This is the messages data (
            {
            body = "Hi";
            endswaptime = "<null>";
            "first name" = Brittany;
            name = Brittany;
            nid = 1803;
            "node_title" = "Re:";
        },
            {
            body = "It is brittany";
            endswaptime = "<null>";
            "first name" = Brittany;
            name = Brittany;
            nid = 1804;
            "node_title" = "Re:";

        },
            {
            body = "Hellooo :)\n";
            endswaptime = "<null>";
            "first name" = Bob;
            name = "Bob";
            nid = 1805;
            "node_title" = "Re:";


        }
    )

2 个答案:

答案 0 :(得分:0)

将谓词拆分为两个单独的谓词并与NSPredicate *p1 = [NSPredicate predicateWithFormat:@"name contains[cd] %@", @"Brittany"]; NSPredicate *p2 = [NSPredicate predicateWithFormat:@"name contains[cd] %@", @"Bob"]; NSCompoundPredicate *p = [NSCompoundPredicate orPredicateWithSubpredicates:@[p1, p2]]; NSArray *filtered = [self.messages filteredArrayUsingPredicate:p]; 结合可能有帮助吗?

Git Fetch

答案 1 :(得分:-2)

我用快速的语言写作。尝试转换为Objective c。 var str = [“Hello”,“hel”,“hello”]

让predicate1 = NSPredicate(格式:“SELF包含%@”,“你好”) 让predicate2 = NSPredicate(格式:“SELF包含%@”,“helo”) let predicatecompound = NSCompoundPredicate.init(type:.or,subpredicates:[predicate1,predicate2]) print(str.filter {predicatecompound.evaluate(with:$ 0)})

参考: Combining 'AND' and 'OR' Condition in NSPredicate