【问题标题】:Obj-c - How can I check if NSString contains one OR the other?Obj-c - 如何检查 NSString 是否包含一个或另一个?
【发布时间】:2017-09-14 02:38:04
【问题描述】:

我想检查我的 NSString 'name' 是否包含“Brittany”或“Bob”,但下面的代码似乎不能解决问题?

ViewController.m

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

知道这应该是什么样子吗?我似乎无法正确使用语法。问题是“过滤”没有返回字符串名称包含“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:";


        }
    )

【问题讨论】:

  • 您是否尝试过将单个谓词拆分为两个单独的谓词并与 NSCompoundPredicate 结合?
  • 我没有 - 你能告诉我那会是什么样子吗?感谢您的帮助!
  • 您发布的代码有什么问题?它看起来是正确的。当然,很大程度上取决于self.messages 中实际包含的数据类型。使用有关其内容的详细信息更新您的问题。
  • @rmaddy 查看更新:)

标签: objective-c nspredicate


【解决方案1】:

也许将谓词分成两个单独的谓词并与NSCompoundPredicate 结合会有所帮助?

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];

【讨论】:

  • 我被抛出错误:“在该块的第三行没有选择器 'orPredicateWithSubPredicates' 的已知类方法?
  • 道歉。它应该是 orPredicateWithSubpredicates。我在脑海中输入了方法名称。
  • @Brittany 如果这有效,那么您的原始代码应该有效。也许你在某个地方打错字了。
  • 很高兴它成功了!我同意@rmaddy。原始代码应该可以工作,但我知道我过去遇到过这种事情,这就是我建议它的原因......
【解决方案2】:

我用 swift 语言写的。尝试转换为Objective c。 var str = ["你好", "hel","你好"]

let predicate1 = NSPredicate(格式: "SELF contains %@","Hello") let predicate2 = NSPredicate(format: "SELF contains %@","helo") 让 predicatecompound = NSCompoundPredicate.init(type: .or, subpredicates: [predicate1,predicate2]) print(str.filter { predicatecompound.evaluate(with: $0) })

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

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 2011-06-09
    • 2015-05-30
    • 2017-05-30
    • 1970-01-01
    • 2017-08-04
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多