Search code examples
iosswiftnspredicate

Filter with NSPredicate on custom object in Swift 3+


I want to filter on my custom object. My custom object look

class Requestlist: NSObject, NSCoding {
let artist: String
let title: String
let id: String
let type: String

init(artist: String, title: String, id: String, type: String) {
    self.artist = artist
    self.title = title
    self.id = id
    self.type = type
   }
}

But the program keeps crashing with this code:

    let textInput = txbSearch.text
    let pred = NSPredicate(format: "ANY artist contains[c] %@ OR title contains[c] %@",textInput!)
    let filteredArray = (Constants.liveRequestlist as NSArray).filtered(using: pred)
    print(filteredArray)

The code runs on KeyboardChange and must be updated when the keyboard input change like a live search. I also want to search on a part of an artist or title. (Like the SQL Like operator)


Solution

  • Two issues:

    • Any is only for key paths or to-many relationships.
    • The second parameter (representing the second %@) is missing.

      let pred = NSPredicate(format: "artist contains[c] %@ OR title contains[c] %@",textInput!, textInput!)
      

    It's highly recommended to use the native Swift filter API:

    let filteredArray = Constants.liveRequestlist.filter{ $0.artist.range(of: textInput!, options: [.caseInsensitive]) != nil 
                                                   || $0.title.range(of: textInput!, options: [.caseInsensitive]) != nil }