Objective-Cプログラミングの初心者です。iOS NSMutableArrayのinsertObjectインデックスが範囲外にある
NSMutableArrayに格納されている単一の数値をテーブルビューに追加する簡単なアプリケーションを作成しようとしています。
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Test App";
self.navigationItem.leftBarButtonItem = self.editButtonItem;
addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItem)];
self.navigationItem.rightBarButtonItem = addButton;
self.itemArray = [[NSMutableArray alloc] initWithCapacity:100];
}
- (void)addItem {
[itemArray insertObject:@"1" atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
このライン
[itemArray insertObject:@"1" atIndex:0];
次のエラーを生成します:
*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
インデックス0が境界を超えているのはなぜここ
でのaddItemための初期化コード及びコード()メソッドであります空の配列と私は間違って何をしているのですか?
UPD
BPが指摘したように、配列への挿入は、空の配列のために動作しない場合がありますので、私は次のチェックを追加しました:
if ([itemArray count] == 0) {
[itemArray addObject:@"1"];
} else {
[itemArray insertObject:@"1" atIndex:0];
}
ので
今、私は同じエラーメッセージを取得しますが、ラインで
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
何が間違っているかに関するアイデアはありますか?
ありがとうございました。しかし、今私は同じエラーが2行下になる。何が問題なの? – IvanR