1

我正在开发一个具有搜索功能的 iPhone 应用程序,其中在 UISearchBar 中编写搜索词会更改(过滤)下面的 UITabelView 的输出。

当用户正在编辑搜索栏的内容并删除所有文本时,将执行以下代码

- (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...)

现在,在搜索栏中进行编辑时,这工作得很好:无论您使用退格/删除删除所有文本还是按下“清除”按钮都无关紧要 - 搜索字段被清除并且所有可搜索项目在表中可见看法。按下“取消”按钮也是如此,但在这种情况下,搜索栏当然会退出第一响应者。

但是,当进行搜索并在表格视图中显示一个或多个结果项时(搜索栏已退出第一响应者并且键盘已消失),仍然可以按清除按钮,但会导致应用程序崩溃并显示以下内容信息:

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

看来问题在于重新加载表视图数据,但我无法弄清楚为什么在一种情况下数组的索引会出现问题,而在另一种情况下却没有。

任何人都知道为什么会发生这种情况?所有帮助表示赞赏。

瑞典格雷戈尔

4

3 回答 3

2

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

于 2009-09-01T23:09:52.043 回答
1
(void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
        ... 
        [searchBar becomeFirstResponder]; 
 [self.tableView reloadData];
于 2009-11-21T21:33:53.750 回答
0

如果搜索字段包含,您可以尝试覆盖- (BOOL)acceptsFirstResponder并返回,但数组. 我认为这应该有效。NO@""!= nil

于 2009-11-06T22:40:59.480 回答