iOS UITableview删除带有动画的行



我看到了很多关于它的问题,但没有找到解决问题的方法。

我有一个带有自定义单元格的表视图。在每个牢房里我都有一个计时器。时间到了,我会发送一条消息删除该行(这不是我使用消息接收的唯一地方)。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView{
    return 1;
}
- (void) timesup:(NSNotification *)notification{
    Data *data = notification.userInfo[@"data"];
    NSUInteger index = [datas indexOfObject:data];
    NSArray *deleteIndexPaths = [[NSArray alloc] initWithObjects:
                                 [NSIndexPath indexPathForRow:index inSection:0],
                                 nil];
    [datas removeObjectAtIndex:index];
    [self.tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    if(datas.count > 0){
        return datas.count;
    }
    // Display a message when the table is empty
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    messageLabel.text = @"No data, pull to refresh";
    messageLabel.textColor = [UIColor blackColor];
    messageLabel.numberOfLines = 0;
    messageLabel.textAlignment = NSTextAlignmentCenter;
    [messageLabel sizeToFit];
    self.tableView.backgroundView = messageLabel;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return 0;
}

我得到了这个错误(取决于我在玩应用程序时有多少数据):

无效更新:节0中的行数无效。更新后现有节中包含的行数(4)必须等于更新前该节中包含行数(6),加上或减去从该节插入或删除的行数,(插入0,删除1)加上或减移入或移出该节的行数。

当我有很多数据超时时,就会出现错误。

注意:如果我不使用"deleteRowsAtIndexPaths",只从数据中删除并重新加载表,它可以完美地工作

昨天我用你建议的方法解决了你在N.B.中写的类似问题。我认为,当表数据源被混淆时,就会出现这个问题。为了克服这种情况,可能的解决方案是为删除行实现正确的流。

BOOL正在删除;

步骤:

  • 当计时器事件触发(调用)时,将isDeleteInProgress设置为YES
  • 如果由于另一个计时器而再次调用,请检查isDeleteInProgress是否为NO,然后仅设置为YES
  • 现在写下面的代码删除行

    [self.tableView开始更新];

    [self.tableView删除RowsAtIndexPaths:deleteIndexPathwithRowAnimation:UITableViewRowAnimationFade];

    [self.tableView endUpdates];

  • 一旦行删除成功,将isDeleteInProgress设置为NO。

这将阻止continuos调用删除,并可能阻止您出现此(未解决的)异常。

我已经阅读了你的评论(任何要显示的代码(一周前开始iOS开发:D)),所以我添加了一个可能对你有帮助的伪代码。

- (void)timerEventFire:(NSTimer*)timer {
    if(!isDeleteInProgress) {
        //write code to delete the rows
        //invalidate timer
        //isDeleteInProgress = NO;
    }
}

祝你好运!

执行以下操作:
1.在类接口中添加一个变量:dispatch_queue_t _deleteQeue;
2.在viewDidLoad中初始化que:
_deleteQeue = dispatch_queue_create("com.delte.qeue", NULL);
3.最后将方法的实现更改为如下所示:

dispatch_sync(_deleteQeue, ^{
    //your deletion code that you have implemented. Deletion from datasource array
    dispatch_async(dispatch_get_main_queue(), ^{
        //cell delete code here. The table animation code. with begin and end updates.
    });
});

***编辑***
让我们试试这个

@synchronized (self) {
    // your deletion code with begin and end updates for the table. Throw away the dispatch code, go back to the old code with Begin and end updates and apply lock. like this.
}

最新更新