iOS 无效行更新异常

标签 ios objective-c multithreading uitableview

我正在制作 iOS 应用的 SMS 样式组件。消息传递 View 是一个 UITableView。我想在表中为已发送消息和传入消息添加一个新行。为传入消息添加行的调用通过专用串行线程通过 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;
}

最佳答案

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

关于iOS 无效行更新异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335573/

相关文章:

ios - 等同于 Swift 中的 performSelectorOnMainThread wait Until Done

iphone - 如何显示指标

python - 如何陷入for循环?

ios - iOS 模拟器的 “Motion Control” 菜单项有什么作用?

ios - 将 UIImages 数组转换为视频时出现黑框

ios - viewDidAppear 在 applicationDidBecomeActive 之前调用

objective-c - 从AppDelegate访问其他Class实例

ios - 是否可以在 UITabBarController 中显示 SFSafariViewController?

multithreading - 使用多线程加载 spring 上下文

Java 同步游戏 : synchronized && wait && notify