【问题标题】:What is predicate to use that contains a word包含单词的谓词使用什么
【发布时间】:2018-02-12 12:27:05
【问题描述】:

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

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

例如: 我有实体人(名字:字符串,姓氏:字符串)。 比方说,我在核心数据中有这个对象: 1) 男人(名字:“John”,第二名字:“Alexandrov”),2) 男人(名字:“Alex”,第二名字:“Kombarov”),3) 男人(名字:“Felps”,第二名字:“Alexan”) .

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

我怎样才能做到这一点?

【问题讨论】:

  • 您要过滤数据还是排序?谓词只能实现前者。
  • @pbasdf,你的意思是我只能按随机顺序获取对象,我不能在获取请求中将它们排序到特定的顺序?
  • 要在获取结果时对结果进行排序,必须使用 NSSortDescriptor(而不是 NSPredicate)。但是CoreData 有很大的限制:一个fetch 请求只能根据一个属性值(或一对一关系的属性)进行排序。如果您想要更复杂的排序顺序,则需要对 fetch 请求返回的数组进行排序。

标签: swift core-data nspredicate


【解决方案1】:

您可以使用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 的谓词。

如果您想对结果进行排序,您可以将一个或多个NSSortDescriptors 添加到您的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!")
}

这是NSPredicateuseful post 的链接

【讨论】:

  • 接近事实!但我需要检查:first:firstName ==“Alex”,secondName ==“Alex”。然后检查 firstName contains[c] "Alex", secondName contains[c] Alex.
  • Adrian,有了这个谓词,我得到了正确的对象,但我的问题是“我可以将这些对象排序到获取请求中的特定序列吗?”
  • 我不确定您的意思,但您可以在获取请求中添加排序描述符 (NSSortDescriptor)。我会在我的答案中添加一些内容。
  • 好的,我等着。我的意思是,如果该属性(firstName 或 secondName)与某些 searchTextString 完全相同,我想在返回的 arr 中的第一个位置看到这个对象)
  • 我不知道有没有可能
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2018-05-11
    相关资源
    最近更新 更多