我正在尝试将一个项目动态地插入到我的 TableView 中。我的应用程序有一个聊天部分,它在第 0 部分显示旧消息(在初始化 View Controller 之前从服务器加载),并在第 1 部分显示刚刚发送/接收的消息(最初为零)。加载 View 时,所有“旧”消息都已加载并显示,没有问题。当我尝试插入行时,问题就开始了。这是我正在做的:
[newMessages addObject:newMessage];(newMessage 是我的自定义消息对象的一个实例,newMessages 是我的数据源) .我确认我的数据源现在有 1 个项目(添加前为 0)。然后我调用以下代码:
[self.chatTableView beginUpdates];
[self.chatTableView insertRowsAtIndexPaths:@[[NSIndexPath
indexPathForRow:newMessages.count - 1 inSection:1]]
withRowAnimation:UITableViewRowAnimationBottom];
[self.chatTableView endUpdates];
我的应用程序在 endUpdates 方法崩溃,给我这个错误:*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex :]: 对象不能为 nil'
我立即检查了 newMessage 是否为 nil,它是 not nil(并重新检查了我的数据源)所以数据源不是问题。我认为 indexPathForRow:newMessages.count - 1 可能是问题所在,并尝试了不同的值(count - 2、count、count + 1)以防万一我遗漏了什么。在这些情况下,我收到另一个错误:'NSInternalInconsistencyException',原因:'尝试将第 1 行插入第 1 节,但更新后第 1 节中只有 1 行'。错误说明了一切,所以问题也不在于 indexPathForRow:newMessages.count - 1。
我在 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法中添加了断点,以查看它何时被准确调用以及返回什么。似乎根本没有调用该方法,断点没有命中(它确实在第一次加载 View 并正确加载初始数据时命中,而且我没有在任何地方设置数据源,所以委托(delegate)/数据源也已连接正确)。我立即检查了其他方法:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if(section == 0){
return @"Eski mesajlar";
}else{
return @"Yeni mesajlar";
}
}
这些方法返回正确的值。我在 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 中放置了一个断点,以查看它何时被调用。它显然是 在 [self.chatTableView endUpdates]; 方法中调用的(从线程/队列的调用堆栈中可以看出),但是 [self.chatTableView endUpdates ]; 甚至没有进入 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法就立即抛出错误。我看过示例(以及其他一些示例),例如:
我已经阅读了那里的答案,但没有一个对我有帮助。我做错了什么?
最佳答案
你有 tableView:estimatedHeightForRowAtIndexPath: 实现吗?我注意到我自己的一个使用 NSFetchedResultsController 的应用程序内部存在类似问题,当调用 tableView:endUpdates 时,应用程序会崩溃并显示相同的错误消息。注释掉 tableView:estimatedHeightForRowAtIndexPath: 为我修复了它。
关于ios - UITableView insertRowsAtIndexPaths 抛出 __NSArrayM insertObject :atIndex :'object cannot be nil' error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22205247/