'How to apply predicate on fullname by combining firstname & lastname of the person entity in ios
I have "Person" entity in coredata with firstname, middlename & lastname. Now, i want to perform predicate search on fullname (combination of fn,mn,ln). Fullname is not an attribute of the entity. I am trying to fetch using nsfetchresultcontroller. E.g If I search "Jone Smith" it shows blank but if i search "John" then it shows records. Do reply.
Solution 1:[1]
There could be various numbers of solutions. One of them is when we are trying to find a person with a full name, and we are not sure in what order the name user enter the name Name and Lastname or Lastname and Name.
Swift 5.0
// First we make components from incoming search text `searchText`
let text = searchText.trimmingCharacters(in: .whitespaces)
let nameComponents = searchText.components(separatedBy: .whitespacesAndNewlines).compactMap { $0.isEmpty ? nil : $0 }
// Next we create predicate trying to find each component in name or lastname
let predicates = nameComponents.map { NSPredicate(format: "name contains[c] %@ OR lastname contains[c] %@", $0,$0) }
// Create `And` predicate
let andPredicate = NSCompoundPredicate.init(andPredicateWithSubpredicates: predicates)
// Use predicates in created `request`
request.predicate = andPredicate
Also, in the same way, there could be used middle name.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
