我需要在从核心数据数组返回的对象中使用哪个谓词:
- 第一个对象必须完全匹配;
- 其他对象必须只包含特定的单词;
例如: 我有实体 Man(firstName:String, lastName: String)。 比方说,我在核心数据中有这个对象: 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")]
我怎样才能做到这一点?
最佳答案
您可以使用 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
的谓词。
如果你想对结果进行排序,你可以在你的NSFetchRequest
中添加一个或多个NSSortDescriptor
:
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!")
}
这是一个指向 useful post 的链接在 NSPredicate
关于swift - 包含单词的谓词是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48746499/