【发布时间】:2023-04-05 20:08:01
【问题描述】:
我正在尝试将项目动态插入到我的表格视图中。我的应用程序有一个聊天部分,它在第 0 部分显示旧的(在初始化视图控制器之前从服务器加载)消息,并在第 1 部分显示刚刚发送/接收的消息(最初为零)。加载视图时,所有“旧”消息都已加载并显示,没有问题。当我尝试插入行时,问题就开始了。这是我正在做的事情:
- 我首先通过添加一个额外项来更新我的表格视图的数据源:
[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:]: object cannot be nil'
我立即检查了newMessage 是否为nil,它不是 nil(并重新检查了我的数据源)所以数据源不是问题。我认为indexPathForRow:newMessages.count - 1 可能是问题所在,并尝试了不同的值(count - 2、count、count + 1),以防万一我遗漏了什么。在这些情况下,我收到另一个错误:'NSInternalInconsistencyException', reason: 'attempt to insert row 1 into section 1, but there are only 1 rows in section 1 after the update'。错误说明了一切,所以问题也不在于indexPathForRow:newMessages.count - 1。
我在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法中添加了断点,以查看它何时被准确调用以及返回什么。似乎根本没有调用该方法,断点没有命中(它确实在第一次加载视图并正确加载初始数据时命中,并且我没有在任何地方设置数据源,因此委托/数据源也已连接正确)。我立即检查了其他方法:
-(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 方法。我见过一些例子(以及其他一些例子),例如:
- how to properly use insertRowsAtIndexPaths?
- Error creating row in tableview
- Add cell to bottom of UITableView in iOS
- Tableview crashes when moving more than half the cells to another section
我已经阅读了那里的答案,但没有一个对我有帮助。我做错了什么?
【问题讨论】:
标签: ios ios7 uitableview