对一个查询字符串进行多次比较

对一个查询字符串进行多次比较

本文介绍了NSPredicate 对一个查询字符串进行多次比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以简化 NSPredicate,它接受多个比较目标的单个查询字符串.我正在为同一查询字符串搜索核心数据实体的多个属性.我当前的查询看起来像这样...

I was wondering if there is a way to simplify an NSPredicate that takes in a single query string for multiple comparison targets. I'm searching multiple attributes of a core data entity for the same query string. My current query looks something like this...

[NSPredicate predicateWithFormat:@"(attributeA contains[cd] %@) OR (attributeB contains[cd] %@) OR (attributeC contains[cd] %@)", searchString, searchString, searchString];

请注意,这非常有效,但看起来确实有点难看.尤其是searchString, searchString, searchString 部分.任何有关如何简化此操作的提示都会很棒!

Note that this works perfectly, but it does look a bit unsightly. Especially the searchString, searchString, searchString part. Any tips on how I could possibly simplify this would be great!

谢谢!

推荐答案

您可以将 NSCompoundPredicate 用于您的 OR &像这样的 AND 操作.

You can use NSCompoundPredicate for your OR & AND operations like this.

Obj-C - 或

// OR Condition //

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"X == 1"];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"X == 2"];
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicate1, predicate2]];

Obj-C - AND

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"X == 1"];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"X == 2"];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate1, predicate2]];

Swift - 或

let predicate1:NSPredicate = NSPredicate(format: "X == 1")
let predicate2:NSPredicate = NSPredicate(format: "Y == 2")
let predicate:NSPredicate  = NSCompoundPredicate(orPredicateWithSubpredicates: [predicate1,predicate2] )

Swift - AND

let predicate1:NSPredicate = NSPredicate(format: "X == 1")
let predicate2:NSPredicate = NSPredicate(format: "Y == 2")
let predicate:NSPredicate  = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2] )

Swift 3 - 或

    let predicate1 = NSPredicate(format: "X == 1")
    let predicate2 = NSPredicate(format: "Y == 2")
    let predicateCompound = NSCompoundPredicate.init(type: .or, subpredicates: [predicate1,predicate2])

Swift 3 - AND

    let predicate1 = NSPredicate(format: "X == 1")
    let predicate2 = NSPredicate(format: "Y == 2")
    let predicateCompound = NSCompoundPredicate.init(type: .and, subpredicates: [predicate1,predicate2])

这篇关于NSPredicate 对一个查询字符串进行多次比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 11:30