2011-05-11 76 views
0

我正在使用下面的代碼來刷新我剛剛添加了一行的tableview。如果表中至少有1行,則該代碼適用於向表中添加行。但是,如果最初是空表,它會崩潰。如果最初爲空表,將行添加到UITableView崩潰

NSArray *indexPaths = [NSArray arrayWithObjects: [NSIndexPath indexPathForRow:[commentsArray count] inSection:0], nil]; 

[commentsTableView beginUpdates]; 

[commentsArray addObject:newestEntry]; 
[commentsTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom]; 

[commentsTableView endUpdates]; 

[commentsTableView scrollToBottom:YES]; 

碰撞響應我得到的是:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).' 

有人能幫助我嗎?

回答

1

嗯,錯誤告訴你UIKit在你更新之前和之後調用tableView:numberOfRowsInSection時返回0。因此,無論是在該方法還是在更新中都有錯誤。您在之前的回答中表示您的tableView:numberOfRowsInSection是正確的,那麼它必須是更新。如果commentsArray由於某種原因可能可以解釋的事情在第一次更新中爲零。也許嘗試以下方法:

NSAssert(commentsArray, @"commentsArray is nil"); 
[commentsArray addObject:newestEntry]; 

在發佈版本中,斷言將被忽略,因此請使用調試版本。

+0

非常感謝您。事實證明,當HTTP請求用空字符串響應時,我的數組甚至沒有被分配!謝謝! – quantum 2011-05-12 07:42:02

+0

不客氣!我不喜歡這樣一個事實,即Objective-C允許你在沒有抱怨的情況下用零來做東西,所以在被咬了幾次之後,我開始習慣於在任何一個零對象都會咬我的地方使用NSAssert。我最近被咬得很少;-) – idz 2011-05-12 07:53:50

0

只要確保用於更新的陣列與重新加載表時使用的陣列相同即可。

//自定義表格視圖中的行數。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    return [commentsArray count]; 
} 

如果這不能解決您的問題,請在這裏輸入一些代碼。

+0

感謝您的回覆。我不知道我應該發佈什麼其他代碼來澄清這一點..我的'numberOfRowsInSection'是正確的。我實際上使用'ASIHTTPRequest'發出POST請求,並且在成功響應委託方法中調用上述代碼塊。流程是我使用POST發佈評論,然後當它返回成功時,我重新分析feed,將新評論'newestEntry'添加到'commentsArray',然後更新'commentsTableView'。 – quantum 2011-05-11 13:18:58