ios - Searching through objects in array swift -
i'm trying create search function using uisearchcontroller. cant seem make work team object. i've started creating team object contain id, name , shortname. i'm retrieving teamdata url , adding team objects array populated tableview. tableview contain searchcontroller suppose filter data, nothing happens.
arrays
var teamarray = array<team>() var filteredtabledata = [string]()
getteams function
func getteams(url: string) { isapicalling = true request(.get, url, parameters: nil) .response { (request, response, data, error) in if error == nil { let data: anyobject = data! let jsonarray = json(data: data as! nsdata) (key: string, subjson: json) in jsonarray { // create object , parse json 1 one append array var newteamobject = team(id: subjson["id"].intvalue, name: subjson["name"].stringvalue, shortname: subjson["shortname"].stringvalue) self.teamarray.append(newteamobject) } self.isapicalling = false self.tableview.reloaddata() self.refreshcontrol?.endrefreshing() } } }
cellforrowatindexpath
override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecellwithidentifier("teamcell", forindexpath: indexpath) as! teamcell cell.textlabel?.font = uifont(name: "helveticaneue-light", size: 20) cell.textlabel?.text = self.teamarray[indexpath.row].name string if (self.cellselected.containsobject(indexpath)) { cell.accessoryview = cell.accessorycheck } else { cell.accessoryview = cell.accessoryuncheck } return cell }
filterdata
func updatesearchresultsforsearchcontroller(searchcontroller: uisearchcontroller) { filteredtabledata.removeall(keepcapacity: false) let searchpredicate = nspredicate(format: "self contains[c] %@", searchcontroller.searchbar.text) let array = (teamarray nsarray).filteredarrayusingpredicate(searchpredicate) filteredtabledata = array as! [string] self.tableview.reloaddata() }
team objects
class team{ var id: int! var name: nsstring! var shortname: nsstring! init(id: int, name:nsstring, shortname: nsstring) { self.id = id self.name = name self.shortname = shortname } }
the objects in teamarray don't have self property. can't use self search in properties of object @ once. have give name of property, , if want search in more 1 have add properties predicate.
i think it's enough search in name property so:
let searchpredicate = nspredicate(format: "name contains[c] %@", searchcontroller.searchbar.text)
if need in more properties this:
let searchpredicate = nspredicate(format: "name contains[c] %@ or shortname contains[c] %@", searchcontroller.searchbar.text, searchcontroller.searchbar.text)
Comments
Post a Comment