クリアボタンを押したときにクラッシュするUISearchBarをアプリに実装しましたが、アイテムが1つ見つかりました。ある文字を入力すると、アプリが1つのアイテムを検索して表示するようなものですが、検索をクリアするとクラッシュします。
stackoverflowを検索しましたが、クリアボタンを押すと配列が空になり、テーブルビューのインデックス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;
}