1
votes

Ok so I am working on implementing a UISearchBar on a tableView that has sections. This may be wrong, but to populate the table view the first time, I have an array with lots of entries, and then populate the sections like this:

if(indexPath.section ==0){

            [cell.textLabel setText:[tableData objectAtIndex:indexPath.row]];                   
    }else if(indexPath.section ==1){

            [cell.textLabel setText:[tableData objectAtIndex:indexPath.row+4]];                     
    }else if(indexPath.section ==2){

            [cell.textLabel setText:[tableData objectAtIndex:indexPath.row+8]];                     
    }

Which is far from elegant, but it works. Now I am trying to hookup the UISearchBar, and this is the method that I am running into issues with:

   - (void)searchBar:(UISearchBar *)sBar textDidChange:(NSString *)searchText
    {
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""] || searchText==nil){
    [tableView reloadData];
    return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSRange r = [name rangeOfString:searchText];
    if(r.location != NSNotFound)
    {

            [tableData addObject:name];

    }

    [pool release];
}

[tableView reloadData];
  }

So I am making an array again of entries that fit the search criteria, but then when I am trying to reload my tableView, it gets all bungled up because it is expecting sections. But all I want is the results in just a plain section-less tableView.

How can I implement this UISearchBar with a tableView with sections?

Thanks

2
Keep different arrays for different section. - Anish

2 Answers

0
votes

set a BOOL when you enter search and adjust your section count accordingly

e.g.

in viewDidLoad

 BOOL isSearching = NO;

set to YES when you enter the textDidChange method.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    int t;
if (isSearching) t = 1
else {
t=  array.count;
}
return t;
}
0
votes

You don't need to keep another variable around; just interrogate the tableView argument to see who is asking for the number of sections. For example, suppose your data is available in a fetchedResultsController:

   if (tableView == self.searchDisplayDisplayController.searchResultsTableView) {
      // your table is the search results table, so just return 1
      return 1;
   } else {
      // your table is your "own" table
      return [[self.fetchedResultsController sections] count];
   }

I do the same thing in many of my table view delegate and data source methods.