2012-02-08 3 views
0

私は自分の画面の一つにBar Button Itemを持っています。ボタンを押すと、ViewControllerのaddItemアクションがトリガーされます。このiOS ViewControllerアクションが例外を起動するのはなぜですか?

- (IBAction)addItem 
{ 

    // items is an Array storing list items 
    int newRowIndex = [items count]; 

    ChecklistItem *item = [[ChecklistItem alloc] init]; 
    item.text = @"I am a new row"; 
    item.checked = NO; 
    [items addObject:item]; 

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:newRowIndex inSection:0]; 
    NSArray *indexPaths = [NSArray arrayWithObject:indexPath]; 
    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic]; 
} 

私はボタンを押すとアプリケーションが終了すると、この例外発生します。この例外が発生している理由

GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Thu Nov 3 21:59:02 UTC 2011) 
Copyright 2004 Free Software Foundation, Inc. 
GDB is free software, covered by the GNU General Public License, and you are 
welcome to change it and/or distribute copies of it under certain conditions. 
Type "show copying" to see the conditions. 
There is absolutely no warranty for GDB. Type "show warranty" for details. 
This GDB was configured as "x86_64-apple-darwin".Attaching to process 1799. 
2012-02-08 16:04:08.146 Checklists[1799:f803] *** Assertion failure in -[_UITableViewUpdateSupport _computeRowUpdates], /SourceCache/UIKit_Sim/UIKit-1912.3/UITableViewSupport.m:386 
2012-02-08 16:04:08.149 Checklists[1799:f803] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid table view update. The application has requested an update to the table view that is inconsistent with the state provided by the data source.' 
*** First throw call stack: 
(0x13bb052 0x154cd0a 0x1363a78 0x99b2db 0x26eb49 0x27c0e3 0x95e3a 0xa182a 0xa1869 0x2e7d 0x13bcec9 0x155c2 0x250d54 0x13bcec9 0x155c2 0x1555a 0xbab76 0xbb03f 0xba2fe 0x3aa30 0x3ac56 0x21384 0x14aa9 0x12a5fa9 0x138f1c5 0x12f4022 0x12f290a 0x12f1db4 0x12f1ccb 0x12a4879 0x12a493e 0x12a9b 0x1ec8 0x1e25) 
terminate called throwing an exceptionsharedlibrary apply-load-rules all 
Current language: auto; currently objective-c 

は誰が説明できますか?

答えて

1

新しい行を挿入しようとする前に、あなたが更新のためにテーブルを準備する必要があります。

-(void)tableView:(UITableView *)tableview numberOfRowsInSection 

戻る最もアップツー:

[[self tableview] beginUpdates]; 

[[self tableview] insertRowsAtIndexPaths ... 

[[self tableview] endUpdates]; 

また、それはあなたが重要ですあなたが呼び出した時の日付の行数:

[tableview endUpdates]; 

numberOfRowsメソッドはretuあなたのアイテム配列内のオブジェクトの数をカウントすると、あなたはすばらしいはずです...

+0

ああ - 私はtableView:numberOfRowsInSectionをスタブして、常に5を返します。これを 'return [items count]'に変更すると、問題。 – bodacious

+0

また、この場合、 '[[self tableview] beginUpdates];と' [[self tableview] endUpdates]; 'は必要ではありませんでした。 - ありがとうございました。 – bodacious