将UITableView行拖动到其他部分会导致崩溃

时间:2017-12-02 15:31:11

标签: ios objective-c uitableview nsmutablearray

目前我一直在尝试编写一个UITableView父控制器来监视它的tableView的当前状态。这个tableView有2个部分,我的计划是每个部分有一个NSMutableArray,它将镜像当前布局,以便稍后保存到NSUserDefaults页面。它以编辑模式显示,标志允许用户使用Apple的默认拖动实现

我的当前- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath因为未知原因而导致横截面拖动不断崩溃我在同一部分中移动一行时保持数组有条理没有问题,但我无法解决即使在尝试手动刷新行时也会出现此问题。所有的cell.reuseIdentifier都是由我提供的。独特,所以我相信没有任何编译器误解

以下是该方法的外观

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
  if (sourceIndexPath != destinationIndexPath) { //not in the same spot
    //same section, different row only, works without issues
    if (sourceIndexPath.section == destinationIndexPath.section) {
          UITableViewCell * cell = [tableView cellForRowAtIndexPath:sourceIndexPath];
      if (destinationIndexPath.section == 0) {
        [self.visibleSections removeObject:cell.reuseIdentifier];
        [self.visibleSections insertObject:cell.reuseIdentifier atIndex:(int)destinationIndexPath.row];
      }
      else if (destinationIndexPath.section == 1) {
        [self.hiddenSections removeObject:cell.reuseIdentifier];
        [self.hiddenSections insertObject:cell.reuseIdentifier atIndex:(int)destinationIndexPath.row];
      }
    }

    //moving to different section
    else {
        NSString * id = [tableView cellForRowAtIndexPath:sourceIndexPath].reuseIdentifier;
        if (id.length != 0) {
             //movedf from visible to hidden
          if (sourceIndexPath.section == 0) {
            [self.visibleSections removeObject:id];
            [self.hiddenSections insertObject:id atIndex:(int)destinationIndexPath.row]; //CRASHING HERE
          }
          //moved from hidden to visible
          else {
            [self.hiddenSections removeObject:id];
            [self.visibleSections insertObject:id atIndex:(int)destinationIndexPath.row]; //CRASHING HERE
          }
       }
    }
}

从记录每一行开始,我已经确定崩溃通常似乎在-(void)insertObject:atIndex:上,在某些情况下我已经尝试过puttng [tableView begin/endUpdates],它可以在各段之间进行一次拖动但总是会崩溃在随后的拖拽中,但它也导致了多个带有隐形行的UI错误,这让我觉得它不是可行的路线。我尝试异步执行我的数组重新排序,但这也是一次立即崩溃

最终我希望能够获得tableView当前顺序的表示,这样我就可以将其保存到我的NSUserDefaults中,以便在将来使用时保持用户所需的顺序,并且如果有人有解决此问题的话,我将不胜感激/跟踪状态的更好方法。感谢

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解代码而且我错过了hiddenSections / visibleSections定义,但我认为你错过了某些东西(如果我误解,我会道歉)。

  1. 重用标识符应与所有类似的单元格相同。这就是为什么它被称为重用。这样,当滚动时单元格移出视图时,可以重用对象UITableViewCell并插入文本值而无需重新创建它。
  2. 您似乎将值存储在重用值中。这样,您可以从一个数组中删除该值并将其添加到另一个数组中。然而,(这是一个很大的猜测),你似乎并没有把它存储在任何地方。我希望你做的事情如下:
  3. NSString *temp = [self.visibleSections removeObject:id]; [self.hiddenSections insertObject:temp atIndex:(int) destinationIndexPath.row];

    1. 我认为发生的事情是,在同一部分中,UITableViewCell的使用时间足够长。但是,当移动到不同的部分时,垃圾收集会在之前的步骤中释放单元格。