Pieter
Pieter

Reputation: 2691

Search property from class in array within UITableView

Context: Swift, iOS8-9, UITableView, UISearchController. Code based on this example: http://www.ioscreator.com/tutorials/add-search-table-view-tutorial-ios8-swift

func updateSearchResultsForSearchController(searchController: UISearchController) {
    filteredTableData.removeAll(keepCapacity: false)
    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    let scores = (allScores as NSArray).filteredArrayUsingPredicate(searchPredicate)
    filteredTableData = scores as! [Score]
    tableView.reloadData()
}

Problem: my data are from a class Score which has a property name and that is what I need to look in (ideally name and topic, but with name I'd be happy for now). So allScores as NSArray is not working because Score does not contain text, but the name property does. How can I implement that here? Something like allScores.name is obviously not working, but I don't know how to call the name property of all items in an array in general.

Upvotes: 1

Views: 120

Answers (1)

hennes
hennes

Reputation: 9342

If you want to use NSPredicate, derive your Score class from NSObject and simply use the property name in the predicate (no SELF required).

class Score: NSObject {
    var name: String

    init(name: String) {
        self.name = name
    }

    override var description: String {
        return self.name
    }
}

let allScores = [Score(name: "a"), Score(name: "ab"), Score(name: "b")]
let searchPredicate = NSPredicate(format: "name CONTAINS[c] %@", "b")
let scores = (allScores as NSArray).filteredArrayUsingPredicate(searchPredicate)
print(scores)

The above snippet prints [ab, b] on the console.

However, you can achieve the very same result by using Swift's filter method.

let allScores = [Score(name: "a"), Score(name: "ab"), Score(name: "b")]
let scores = allScores.filter { $0.name.containsString("b") }
print(scores)

This snippet again prints [ab, b] on the console which demonstrates its equality to the NSPredicate variant.

Upvotes: 1

Related Questions