如何在UITableView中插入新单元格?

use*_*889 3 iphone xcode objective-c ipad ios

我正在尝试使用添加一行到tableview

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
Run Code Online (Sandbox Code Playgroud)

它抛出一个异常,我调用insertRowsAtIndexPaths:withRowAnimation:,它说

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
Run Code Online (Sandbox Code Playgroud)

它返回正确数量的行和节,但它在抛出异常之前从未进入cellForRowAtIndexPath.我也使用故事板进行此操作,并且我将tableView设置为具有静态单元格,因为大多数tableView实际上都具有静态单元格.我真的不想切换到动态原型,因为我不能使用我正在使用的IBOutlets和IBActions,而且我必须重新开始关于单元格的布局.有没有办法让我摆脱这个异常而不改变我的tableView有动态原型单元格?

编辑

在我发布之前的那一行是

[itemsInCurrentPurchase insertObject:itemName atIndex:0];
Run Code Online (Sandbox Code Playgroud)

应该更新数组.我在用

[itemsInCurrentPurchase count]
Run Code Online (Sandbox Code Playgroud)

对于我在节中的行数,它在更新后返回正确的数字.问题是甚至没有达到cellForRowAtIndexPath方法.在更新期间,还有在行数和可能导致此错误的单元格类型之间调用的其他内容吗?

iDe*_*Dev 9

在插入行之前,您需要使用此新对象更新数据源.否则,在尝试使用此新行更新表视图时会崩溃.

例如: -

[self.dataSourceArray insertObject:object atIndex:indexPath.row];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
Run Code Online (Sandbox Code Playgroud)