我需要使用哪个谓词来自Core Data数组返回的对象:
例如: 我有实体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”)]
我怎样才能实现这个目标?
答案 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
答案 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!")
}