iOS:使用 insertRowsAtIndexPaths 在 UITableview 中插入多行

2024-04-06

我在 TableView 中已经有 10 行我想做的是添加另外 10 行,因为我正在使用 insertRowsAtIndexPaths 但我收到错误。

以下是我正在使用的代码

-(void)insertDownloadedActions:(NSMutableArray *)dataToAdd
{
        __weak CurrentViewController *weakSelf = self;

        int64_t delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [weakSelf.tableView beginUpdates];
            [weakSelf.dataSource addObjects:dataToAdd];
            NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:[weakSelf.dataSource count]-dataToAdd.count-1 inSection:0];
            [weakSelf.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationTop];
            [weakSelf.tableView endUpdates];
        });
}

但我收到以下错误

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (20) must be equal to the number of rows contained in that section before the update (10), 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)insertDownloadedActions:(NSMutableArray *)dataToAdd
{
    // don't need this
    //__weak CurrentViewController *weakSelf = self;

    int64_t delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {

        // build the index paths for insertion
        // since you're adding to the end of datasource, the new rows will start at count
        NSMutableArray *indexPaths = [NSMutableArray array];
        NSInteger currentCount = self.datasource.count;
        for (int i = 0; i < dataToAdd.count; i++) {
            [indexPaths addObject:[NSIndexPath indexPathForRow:currentCount+i inSection:0]];
        }

        // do the insertion
        [self.dataSource addObjects:dataToAdd];

        // tell the table view to update (at all of the inserted index paths)
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];
    });
}

您希望使用weakSelf来避免块所有者保留块并且块(通过使用块所有者“self”)保留所有者的循环。这里不需要weakSelf模式,因为视图控制器不保留分派块的副本。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS:使用 insertRowsAtIndexPaths 在 UITableview 中插入多行 的相关文章

随机推荐