包含单词的谓词是什么

What is predicate to use that contains a word

我需要在从核心数据数组返回的对象中使用哪个谓词:

  1. 第一个对象必须完全匹配;
  2. 其他对象必须只包含特定的单词;

例如: 我有实体 Man(firstName:String, lastName: String)。 比方说,我在核心数据中有这个对象: 1)男人(名字:"John",第二个名字:"Alexandrov"),2)男人(名字:"Alex",第二个名字:"Kombarov"),3)男人(名字:"Felps", secondName: "Alexan").

在返回的 arr 中我想看到 [Man(firstName: "Alex", secondName: "Kombarov"), Man(firstName: "Felps", secondName: "Alexan" ), 男(名: "John", 名: "Alexandrov")]

我怎样才能做到这一点?

你可以使用 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

上的 link 到 useful post

添加到@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!")
    }