2012-02-08 62 views
0

我在我的一個屏幕上有一個酒吧按鈕項目。按下按鈕時,應該在我的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

在嘗試插入新行,你必須準備更新表:

[[self tableview] beginUpdates]; 

[[self tableview] insertRowsAtIndexPaths ... 

[[self tableview] endUpdates]; 

此外,重要的是你:

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

返回最-UP-TO-您撥打電話時的行數:

[tableview endUpdates]; 

假設numberOfRows方法只返回rns在你的物品陣列中的對象的數量,你應該沒問題...

+0

啊 - 我將stubbed tableView:numberOfRowsInSection總是返回5.改成這個'return [items count]'似乎已經修復了問題。 – bodacious 2012-02-08 16:16:40

+0

此外,在這種情況下,'[[self tableview] beginUpdates];''[[self tableview] endUpdates];'雖然不是必需的。 - 非常感謝你的幫助 – bodacious 2012-02-08 16:17:16

相關問題