2010-12-05 11 views
0

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

insertRowsAtIndexPaths:withRowAnimationに電話すると、beginUpdatesendUpdatesの間になるはずです(tableView)。

TableView Programming Guideを確認してください。

0

initWithCapacityメソッドは、オブジェクトのメモリだけを確保しますが、配列に指定されたオブジェクトの数は実際には作成されません。

まだオブジェクトがない配列に挿入できるかどうかわからないため、配列数が0の場合はaddObjectメソッドを使用し、そうでない場合はinsertObjectメソッドを使用します。

+0

ありがとうございました。しかし、今私は同じエラーが2行下になる。何が問題なの? – IvanR

関連する問題