iOS 无效行更新异常

iOS Invalid Row Update Exception

我正在制作 iOS 应用程序的 SMS 样式组件。消息传递视图是 UITableView。我想在 table 中为已发送消息和传入消息添加一个新行。为传入消息添加行的调用通过专用串行线程通过 KVO 进行。类似地,通过 KVO 发送成功,为已发送消息添加一行的调用来自不同的专用串行线程。如果在几乎完全相同的时间有一个从传入消息中添加行的调用和另一个为已发送消息添加行的调用,应用程序将抛出无效行的异常:

'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (31) must be equal to the number of rows contained in that section before the update (29), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

这是线程安全问题吗?我该如何解决?这是从两个不同线程调用的相关方法:

-(void)addRowToMessageTable {    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow: [_messageTable numberOfRowsInSection:0] inSection: 0];
        [_messageTable beginUpdates];
        [_messageTable insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [_messageTable endUpdates];
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _privateMessages.count;
}

Table 视图更新方法在内部再次加载 table,因此它再次调用委托方法。您收到异常是因为您已将行添加到 table 但尚未将该对象添加到 _privateMessages 数组。将相同的对象添加到数组,以便更新前后的计数相同。