【问题标题】:TableView reloadData restarts NSTimer in UITableViewCellTableView reloadData 重启 UITableViewCell 中的 NSTimer
【发布时间】:2014-06-11 18:38:15
【问题描述】:

我有一个UITableView 的自定义单元格。每个单元格都有一个NSTimer,可由用户设置并通过点击按钮启动。除非将新单元格添加到 TableView 中,否则计时器将起作用。在 unwind 方法(来自为新单元格创建新对象)中,我必须重新加载 TableView 中的数据,以便出现新单元格。然而,这会重新加载所有单元,导致任何正在运行的计时器重新启动。有没有一种方法可以在不重新启动正在运行的计时器的情况下添加单元格?

编辑:

我有一个 ViewController,它创建一个新对象,然后返回 FirstViewController.m 我有一个 unwind 方法,它应该用新对象的一行更新 tableView。使用reloadData 方法将不起作用,因为它会重新加载所有单元格。我想只添加一个新单元格而不重新加载整个 tableView。

-(IBAction)unwind:(UIStoryboardSegue *)segue {
    ABCAddItemViewController *source = [segue sourceViewController];
    ABCItem *item = source.object;

    if (item != nil) {
        [self.objectArray addObject:item];

        [self.tableView reloadData];
    }
}

为此,我尝试添加这些行而不是 [self.tableView reloadData]

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.objectArray indexOfObject:item] inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

但是,应用程序崩溃并且我收到以下消息:

'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), 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).'

tableView的行数由numberOfRowsInSection:方法中的[self.objectArray count]决定。

【问题讨论】:

    标签: ios uitableview nstimer reloaddata


    【解决方案1】:

    将计时器添加到单元格不是一个好主意,因为它们会被重复使用。它们是视图。我的建议是创建一些对象,这些对象具有您要在这些 UITableViewCells 中显示的文本/信息,并将计时器添加到这些对象。这样计时器信息不会存储在单元格中,它们将存储状态

    【讨论】:

      【解决方案2】:

      只需插入一个单元格,无需重新加载整个表格。你可以像这样添加单元格

      self.tableView beginUpdates];
      [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:section]] withRowAnimation:UITableViewRowAnimationLeft];
      [self.tableView endUpdates];
      

      【讨论】:

      • 当我尝试在我的展开方法中实现这一点时,我得到一个“无效更新”错误。我该如何解决这个问题?
      • 你能添加确切的错误吗?还有一些代码可以了解您的操作方式。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多