1

I have a search bar added in the user interface. The Searchbar is already set, and works, but I can't figure out how to make it search content in the UITableView. Can I just remove the items that do not start with the characters typed in the search bar??

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
if (searchBar.text.length < 1) {
    return;
}
else {
    // Do search stuff here



}}

This code works, the else function is called. But I don't know how to do it. I don't want to create a whole new array just for that.

Alessandro
  • 4,000
  • 12
  • 63
  • 131

1 Answers1

3

I'll do you one better. This example will search as the user types. If your data is quite massive, you may want to implement it in - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar like you originally planned. Unfortunately, you need a second array, but it's easy to code around it in the table:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if(searchText.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {

        isFiltered = true;
        if (filteredTableData == nil)
            filteredTableData = [[NSMutableArray alloc] init];
        else 
            [filteredTableData removeAllObjects];

        for (NSString* string in self.masterSiteList)
        {
            NSRange nameRange = [string rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
            if(nameRange.location != NSNotFound)
            {
                [filteredTableData addObject:string];
            }
        }
    }
    [self.tableView reloadData];
}

then update your delegate methods to show the data of the filteredTableData array instead of the regular array when the isFiltered var is set to YES.

CodaFi
  • 43,043
  • 8
  • 107
  • 153
  • I added the boolen isFilterd, and added this: if(isFiltered != NO){ NSArray *filteredTableData = [[NSMutableArray alloc] init]; cell.textLabel.text = [filteredTableData objectAtIndex:indexPath.row]; } else if(isFiltered != YES){ cell.textLabel.text = [self.itemArray objectAtIndex:indexPath.row]; } return cell; } ...but it doesn't really work – Alessandro Jul 03 '12 at 00:24
  • Yeah. The "adjustments" part is the hardest with sample code. LOL – CodaFi Jul 03 '12 at 01:21