You could use a NSCompoundPredicate
.
First, you'd create a predicate for the firstName
. This one would be strict, so you'd search for matches using ==
:
let firstNamePredicate = NSPredicate(format: "%K == %@", argumentArray: [#keyPath(Man.firstName), "alex"])
Then, you'd create a predicate for the lastName
. This one is less strict, so you'd use CONTAINS
:
let lastNamePredicate = NSPredicate(format: "%K CONTAINS[c] %@", argumentArray: [#keyPath(Man.lastName), "alex"])
Then you'd create an NSCompoundPredicate using the orPredicateWithSubpredicates
signature.
let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [firstNamePredicate, lastNamePredicate])
From there, you could create a NSFetchRequest
and assign compoundPredicate
as the predicate for the fetchRequest
.
If you want to sort the results, you can add one or more NSSortDescriptor
s to your NSFetchRequest
:
let sortByLastName = NSSortDescriptor(key: #keyPath(Man.lastName), ascending: true)
let sortByFirstName = NSSortDescriptor(key: #keyPath(Man.firstName), ascending: true)
request.sortDescriptors = [sortByLastName, sortByFirstName]
Then, you'd do the fetch:
let request: NSFetchRequest = Man.fetchRequest()
request.predicate = compoundPredicate
var results: [Man] = []
do {
results = try context.fetch(request)
} catch {
print("Something went horribly wrong!")
}
Here's a link to a useful post on NSPredicate