UITableView 自定义cell获取所在indexPath的正确方式

总结:

// UITableView 自定义cell获取所在indexPath的正确方式:
// 不要记录cell的indexpath,而是去tableview获取
NSIndexPath *indexPath = [tableView indexPathForCell:cell];

遇到的bug

前提:

  1. cell有个addButton,点击之后会添加新的cell
  2. tableview有侧滑删除的功能
    代码:
// 删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 从数据源中删除
    [self.dataSourceArray removeObjectAtIndex:indexPath.row];
    // 从列表中删除
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
// 添加
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
KapEditorAddCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KapEditorAddCell"];
  [cell.cellAddButton setDidBlock:^(ButtonBase *button) {
      NSIndexPath *insetPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0];
      [self.dataSourceArray insertObject:[[KapEditorAddModel alloc] initWithDictionary:@{}] atIndex:insetPath.row];
      [tableView insertRowsAtIndexPaths:@[insetPath] withRowAnimation:UITableViewRowAnimationNone];
   }];
}

崩溃:
先点击addButton添加了一个cell,然后删除第一个cell,再点击第二个cell的addButton。
越界崩溃

崩溃分析

当add新的cell之后,cell所在的indexpath已经改变,
而block持有的indexpath还未改变,导致insertRowsAtIndexPaths越界。。。。

解决方案

不要记录cell的indexpath,而是去tableview获取

// 核心代码
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
// 更正后的代码
 [cell.cellAddButton setDidBlock:^(ButtonBase *button) {
      NSIndexPath *currentIndexPath = [tableView indexPathForCell:cell];
      NSIndexPath *insetPath = [NSIndexPath indexPathForRow: currentIndexPath.row+1 inSection:0];
      [self.dataSourceArray insertObject:[[KapEditorAddModel alloc] initWithDictionary:@{}] atIndex:insetPath.row];
      [tableView insertRowsAtIndexPaths:@[insetPath] withRowAnimation:UITableViewRowAnimationNone];
   }];

你可能感兴趣的:(UITableView 自定义cell获取所在indexPath的正确方式)