2013-01-05 36 views
3

我想行添加到使用如何在UITableView中插入新單元格?

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 

它拋出一個異常,我叫insertRowsAtIndexPaths一個實現代碼如下:withRowAnimation :,它說

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]' 

它返回正確的行數和部分,但在拋出異常之前,它絕不會將它指向cellForRowAtIndexPath。我正在做一個故事板也是這樣,我有tableView設置爲靜態單元格,因爲大部分tableView確實有靜態單元格。我真的不想切換到動態原型,因爲那時我不能使用IBOutlets和IBAction,而我必須從單元的佈局開始。有沒有辦法讓我擺脫這個異常,而不改變我的tableView有動態的原型單元格?

編輯

線之前什麼好的,我貼是

[itemsInCurrentPurchase insertObject:itemName atIndex:0]; 

這是應該更新數組。我正在使用

[itemsInCurrentPurchase count] 

表示我的行數,它在更新後返回正確的數字。問題是沒有達到cellForRowAtIndexPath方法。在更新過程中還有其他什麼東西在行數和單元類型之間被調用,可能會導致這個錯誤?

+1

你更新插入前的數據源陣列?你需要在調用之前更新它。 – iDev

回答

9

在插入行之前,您需要使用此新對象更新您的數據源。否則在試圖用這個新行更新表視圖時會崩潰。

的如: -

[self.dataSourceArray insertObject:object atIndex:indexPath.row]; 
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
+0

你能解釋一下'@ [indexPath]'是做什麼的嗎?它是否創建一個具有'indexPath'作爲唯一對象的數組? –

+0

@JackHumphries,是的。有關更多詳細信息,請查看http://clang.llvm.org/docs/ObjectiveCLiterals.html – iDev

+0

我這樣做,您有任何其他建議嗎? – user1654889

相關問題