我在我的应用程序中实现了一个 UISearchBar,当我点击清除按钮并且找到一个项目时它会崩溃。就像我输入一些字符,应用程序搜索并显示 1 项,但是当我清除搜索时,它崩溃了。
我搜索了stackoverflow,我知道问题出在保存搜索项的数组上,因为当我点击清除按钮时,数组变为空并且tableview索引path.row无法显示。
此外,如果搜索没有返回任何项目并且我点击了清除按钮,我会收到一条类似的错误消息,这一次购买说我得到了一个空数组。
该应用程序停在这里:
NSDictionary *itemAtIndice =(NSDictionary *)[filteredCodigos objectAtIndex:indexPath.row];
问题是我根本不知道该怎么办!!!
这是错误:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
这是我的代码::
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length == 0) {
isFiltered = NO;
} else {
isFiltered = YES;
filteredCodigos = [[NSMutableArray alloc]init];
for (NSDictionary *item in values) {
NSString *string = [item objectForKey:@"NAME"];
NSRange stringRange = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound) {
[filteredCodigos addObject:item];
}
}
}
[self.tableView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[self.Pesquisa resignFirstResponder];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFiltered) {
return [filteredCodigos count];
}
return values.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSDictionary *itemAtIndex =(NSDictionary *)[values objectAtIndex:indexPath.row];
NSDictionary *itemAtIndice =(NSDictionary *)[filteredCodigos objectAtIndex:indexPath.row];
if (!isFiltered) {
cell.textLabel.text = [itemAtIndex objectForKey:@"SYMBOL"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
cell.detailTextLabel.text = [itemAtIndex objectForKey:@"NAME"];
} else {
cell.textLabel.text = [itemAtIndice objectForKey:@"SYMBOL"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
cell.detailTextLabel.text = [itemAtIndice objectForKey:@"NAME"];
}
return cell;
}