UITableViewのスクロール表示で「NSRangeException」エラー

UITableViewを使ったアプリでセルの内容を書き換えたり
テーブルスクロールの位置指定をしていたら ‘NSRangeException’エラーが
出ました。

■コード

NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[myTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];

■エラー内容

*** Terminating app due to uncaught exception 'NSRangeException', reason: '
-[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:]
: row (0) beyond bounds (0) for section (0).'

テーブルのセル数が0のときにエラーになるようなので
以下のように修正しました。

■修正後のコード

if (([myTableView numberOfSections] > 0) && ([myTableView numberOfRowsInSection: 0] > 0)){
    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [myTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

これでエラーが出なくなりました。
動画の検索でテーブルのセルを検索結果で作成するときに
検索結果が0件の場合のときも考えてプログラムして置いた方が良いです。

タイトルとURLをコピーしました