Search code examples
iosuitableviewnsarrayuisearchbar

How to Search multiple NSArray from UITableView in IOS


What I want is to be able to search a UITableView, and have other arrays be narrowed down to the results of the cell's textlabel array. That probably just made no sense to no one. Here's an example.

An array called titleArray that fills the cell's textLabel:

"Toyota Yaris"
"Ford Escape"
"Ford F-150"

Another array called detailArray that fills the detail text label below the textLabel in a cell:

"Car"
"SUV"
"Truck"

When I search for "Ford" I want the UITableView to display the cells like this:

Cell 1: Ford Escape
        SUV

Cell 2: Ford F-150
        Truck

But it is displaying like this:

Cell 1: Ford Escape
        Car

Cell 2: Ford F-150
        SUV

Essentially it narrowed down the titleArray but not the detailArray so it is display objects 1 & 2 from titleArray but 0 & 1 from detailArray. If this confuses you please ask any questions!


Solution

  • In your code, you are likely creating UITableViewCell object in a message named tableView:cellForRowAtIndexPath:. I would review this code for your issue. When you create/retrieve the UITableViewCell, you will then fill in the title and detail (check this in the debugger). I note that the example you are following is creating a pared down array of items in response to your search argument. It seems most likely that you will need to pare down the detail array at the same time you pare down the title array. You may also need to search in your detail array (depending on how you want your app to function). This could complicate your search logic some.

    //Possible search logic
    for (int iii = 0; iii < titleArray.count; iii++) {
        if (<titleArray matches search string>) {
            [titlesToDisplay addObject:[titleArray objectAtIndex:iii]];
            [detailsToDisplay addObject:[detailArray objectAtIndex:iii]];
            //Assuming that you have titles and details in corresponding slots.
        }
    }
    

    Now when you set the title and detail settings for your UITableViewCell, you should count entries in titlesToDisplay and retrieve entries from titlesToDisplay and detailsToDisplay.