2

I have a NSSearchController that searches an array of arrays. An example of this master array is

[["key1',"value1"],["key2","value2"]]

My search function is as follows:

func updateSearchResultsForSearchController(searchController: UISearchController) {
    for (key, val) in zip(self.keys, self.values) {
        pairs.append([key,val])
    }

    filteredKeys.removeAll(keepCapacity: false)
    filteredValues.removeAll(keepCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)
    let searcher = (self.pairs as NSArray).filteredArrayUsingPredicate(searchPredicate)
    println(searcher)

    for matched in searcher {
        var appendedKey = matched[0] as! String
        var appendedValue = matched[1] as! String
        filteredKeys.append(appendedKey)
        filteredValues.append(appendedValue)
    }

    pairs.removeAll(keepCapacity: false)

    self.tableView.reloadData()
}

The problem is with my NSPredicate string, as I am searching an array of arrays, the SELF CONTAINS requires an exact string match to be in the array instead of it just containing it. I really want the subarrays of the master array to contain the string being searched.

I tried "name CONTAINS[c] %@" and "SELF BEGINSWITH[c] %@" Both fail. Does anyone know what predicate string to use to search an array of arrays?

1 Answer 1

3

You need to use ANY SELF.

let pairs = [["key1","value1"],["key2","value2"]]
let searchPredicate = NSPredicate(format: "ANY SELF CONTAINS[c] %@", "lue2")
let searcher = (pairs as NSArray).filteredArrayUsingPredicate(searchPredicate)
println(searcher) // Prints the second element

From the official documentation for ANY:

Specifies any of the elements in the following expression.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.