NSPredicate filter part of array

106 Views Asked by At

I just began coding and I've chosen swift. I have a CoreData database and I use a predicate to display parts of it. It works fine to find a complete expression. What can I do to search in the datafield Strasse.name just a part of a string like "*way". Here is my code:

   let myFetschRequest = NSFetchRequest(entityName: "Strasse")
    var filter1 = "searchword"
    var filter2 = "searchword"
    let predicate1 = NSPredicate(format: "name = %@", filter1)
    let predicate2 = NSPredicate(format: "art = %@", filter2)
    var compound = NSCompoundPredicate.andPredicateWithSubpredicates([predicate1,predicate2])
    myFetschRequest.predicate = compound
    let sortDescriptor1 = NSSortDescriptor(key: "name", ascending: true)
    let sortDescriptor2 = NSSortDescriptor(key: "bereich", ascending: true)
    myFetschRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2]
    daten = context!.executeFetchRequest(myFetschRequest, error: nil) as! [Strasse]
    tableView.reloadData()
2

There are 2 best solutions below

2
On BEST ANSWER

Probably something like:

let filter = "way"
let condition = [NSPredicate(format: "Strasse.name contains[cd] %@", filter]

Just googled it real fast. Will test it later if it works.

Tested and working.

1
On

Try it.

var name = "way" let resultPredicate2 = NSPredicate(format: "Strasse.name BEGINSWITH[cs] %@",name)

this predicate is filter all data, which is start to "way". If you want only a specific string. then use given below.

let resultPredicate2 = NSPredicate(format: "Strasse.name LIKE[cs] %@",name)