0

クリアボタンを押したときにクラッシュする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;
}
4

2 に答える 2

1

filteredCodigosは外部で宣言searchBar:textDidChange:され、複数の場所で使用されますが、で割り当てられsearchBar:textDidChange:ます。ほとんどの場合、他のコードが、filteredCodigos割り当てられていないか空のメンバーにアクセスしようとしています。例外ブレークポイントを有効にすると、それを追跡するのに役立ちます。

補足として。forループの代わりにNSPredicateを調べてアイテムをフィルタリングすることもできます。

于 2013-01-07T05:22:36.313 に答える
0

ついにこの問題を修正することができました。

エラーが発生した行のlastObjectのindexPath.rowを置き換えました。

だから、前に:

NSDictionary *itemAtIndice =(NSDictionary *)[filteredCodigos objectAtIndex:indexPath.row];

以降:

NSDictionary *itemAtIndice =(NSDictionary *)[filteredCodigos lastObject];
于 2013-01-07T06:07:31.260 に答える