views:

1028

answers:

4

I'm working on an iPhone app with a search function, where writing search terms in a UISearchBar changes (filters) the output of the UITabelView below.

When user is editing the content of the search bar and deletes all of the text, the following code is executed in

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

  if([searchText isEqualToString:@""] || searchText==nil){

    [tableData removeAllObjects]; //clear array that holds data for table view
    [tableData addObjectsFromArray:tumorNames]; //load array with database
    [searchTableView reloadData];
    return;
    }
}

(method continues...)

Now, this works just fine when editing inside the search bar: whether you delete all the text with backspace/delete or press the 'clear' button doesn't matter - search field is cleared and all the searchable items are made visible in the table view. Same goes for pressing the 'cancel' button, but in this case, of course, the search bar resigns first responder.

However, when a search has been made and one or more result items are displayed in the table view (search bar has resigned first responder and keyboard is gone), pressing the clear button is still possible, but results in the app crashing with the following message:

'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0)'

It appears that the problem is within the reloading of the table view data, but I cannot figure out why there would be a problem with the index of the array in one case but not in the other.

Anyone knows why this would happen? All help appreciated.

Gregor, Sweden

A: 

Turns out, when the clear button is clicked, the delegate method

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar

gets called after the method

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

This may seem strange, but explains my problem: as I flush the array holding the data for the table view in the former method (to clear last search), I get an error when the table view tries to read from it.

Problem solved, hope this info is helpful to somebody else.

All I need to do now is make the search bar not become first responder when the cancel button is clicked. Anyone know how to do this?

Gregor, Sweden

Gregor
A: 

You could try overriding - (BOOL)acceptsFirstResponder and returning NO if the searchfield contains @"", but the array != nil. I think that should work.

joey
A: 
  • (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText { ... [searchBar becomeFirstResponder]; [self.tableView reloadData];
Yvan
A: 

Hi Gregor, Do you know how to resolve it?

elly