Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data NSPredicate search in multiple Attributes columns

I want to search keywords in Hotels Entity in two attributes (hotelName & cityName)

i'm looking for hotel enter image description here

"The Kensington Studios" is in hotelName Attribute

"London" is cityName Attribute

in search bar, if i type middle of the hotelName and cityName(just like below) it should identify and display the results. enter image description here

to achieve this, i'm doing like

let charSet = CharacterSet(charactersIn: " ") 
let words = searchText.components(separatedBy: charSet) 
let predicate = NSPredicate(format: "(hotelName IN %@) OR (cityName IN %@)", words, words)

But its giving empty results.

Please guide me..

like image 335
Lokesh Chowdary Avatar asked Sep 19 '25 18:09

Lokesh Chowdary


1 Answers

words object returns [String] array. You have to use each object of the array. So the code should be like

let words = searchText.components(separatedBy: " ")
        
        var predicateArr = [NSPredicate]()
        for word in words! {
            let predicate = NSPredicate(format: "(hotelName contains [c]) OR (cityName contains [c])", word, word)
            predicateArr.append(predicate)
        }
        
        
        let compound = NSCompoundPredicate(orPredicateWithSubpredicates: predicateArr)
        let output = array.filtered(using: compound)
like image 77
A K M Saleh Sultan Avatar answered Sep 21 '25 11:09

A K M Saleh Sultan