什么是使用包含单词的谓词

时间:2018-02-12 12:27:06

标签: swift core-data nspredicate

我需要使用哪个谓词来自Core Data数组返回的对象:

  1. 第一个对象必须完全匹配;
  2. 其他对象必须包含特定字;
  3. 例如: 我有实体Man(firstName:String,lastName:String)。 比方说,我在Core Data中有这个对象: 1)Man(firstName:“John”,secondName:“Alexandrov”),2)Man(firstName:“Alex”,secondName:“Kombarov”),3)Man(firstName:“Felps”,secondName:“Alexan”)

    在返回的arr中,我希望看到[Man(firstName:“Alex”,secondName:“Kombarov”),Man(firstName:“Felps”,secondName:“Alexan”),Man(firstName:“John”, secondName:“Alexandrov”)]

    我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:2)

您可以使用NSCompoundPredicate

首先,您要为firstName创建一个谓词。这个是严格的,因此您可以使用==搜索匹配项:

let firstNamePredicate = NSPredicate(format: "%K == %@", argumentArray: [#keyPath(Man.firstName), "alex"])

然后,您要为lastName创建谓词。这个不太严格,所以你要使用CONTAINS

let lastNamePredicate = NSPredicate(format: "%K CONTAINS[c] %@", argumentArray: [#keyPath(Man.lastName), "alex"])

然后,您使用orPredicateWithSubpredicates签名创建NSCompoundPredicate。

let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [firstNamePredicate, lastNamePredicate])

从那里,您可以创建NSFetchRequest并指定compoundPredicate作为fetchRequest的谓词。

如果您想对结果进行排序,可以向NSSortDescriptor添加一个或多个NSFetchRequest

let sortByLastName = NSSortDescriptor(key: #keyPath(Man.lastName), ascending: true)
let sortByFirstName = NSSortDescriptor(key: #keyPath(Man.firstName), ascending: true)
request.sortDescriptors = [sortByLastName, sortByFirstName]

然后,你进行了获取:

let request: NSFetchRequest = Man.fetchRequest()
request.predicate = compoundPredicate

var results: [Man] = []

do {
  results = try context.fetch(request)
} catch {
  print("Something went horribly wrong!")
}

这是NSPredicate

useful post的链接

答案 1 :(得分:0)

除了@Adrian答案之外,我还必须进行一些更改才能使其正常工作。

    let FIRSTNAME = "Alex"
    let LASTNAME = "Smith"
    let firstNamePredicate = NSPredicate(format: "firstName == %@", FIRSTNAME)
    let lastNamePredicate = NSPredicate(format: "firstName == %@", LASTNAME)
    let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [firstNamePredicate, lastNamePredicate])
    request.predicate = compoundPredicate
    do {
      results = try context.fetch(request)
    } catch {
      print("Something went horribly wrong!")
    }