tags:

views:

19

answers:

1

Hi,

I am facing a problem in implementing the search functionality in Table Views... Here is the code i am implementing to search...

- (void) searchTableView {

NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];

searchArray = [data boats];

for(Boat *boat in searchArray)
{
    NSRange titleResultsRange = [[boat boatName] rangeOfString:searchText options:NSCaseInsensitiveSearch];

    if (titleResultsRange.length > 0)
        [copyListOfItems addObject:boat];
}

[searchArray release];
searchArray = nil;

}

When the search bar starts getting edited, i call this...

- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {

//Remove all objects first.
[copyListOfItems removeAllObjects];

if([searchText length] > 0) {

    [ovController.view removeFromSuperview];
    searching = YES;
    letUserSelectRow = YES;
    self.tableView.scrollEnabled = YES;
    [self searchTableView];
}
else {

    [self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];

    searching = NO;
    letUserSelectRow = NO;
    self.tableView.scrollEnabled = NO;
}

[self.tableView reloadData];

}

and i assign the value to table row using...

if(searching)
{
    Boat *copyboat = [copyListOfItems objectAtIndex:[indexPath row]];
    cell.textLabel.text = [copyboat boatName];
    NSLog(@"%@", [copyboat boatName]);
}
else {
    Boat *fullboat =[data.boats objectAtIndex:[indexPath row]];
    cell.textLabel.text =[fullboat boatName];       
}

But when i start typing the values in search bar, the app is crashing. I get different errors when i type different alphabets. I get errors like. * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 6 beyond bounds [0 .. 5]'

or

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'

Sometime its also showing EXEC_BAD_ACCESS also... I am screwed right now. Can anyone please tell me what the error exactly is...???

A: 

When you create the subset of boat names, do you change the value of what you return in numberOfRowsInSection? It looks like the table is reloading and trying to find data for 7 rows, but you now only have data for six. Something like:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
if (searching) {
    return [copyListOfItems count];
} else {
    return [data count];
}

}

joelm