从块中向tableView附加行

时间:2014-11-19 12:56:23

标签: ios uitableview objective-c-blocks

我正在尝试从块中添加/追加行到tableView的单个部分。 问题是,当我添加索引路径(insertRowsAtIndexPaths)时,代码崩溃(更新后的现有部分中包含的行数(12)必须等于更新前该部分中包含的行数(1) yadayadayada)

现在我追溯到这样一个事实:在将额外数据附加到其数据源(也使用weakSelf)后,[weakSelf.tableView numberOfRowsInSection:0]没有更新

任何人都知道我在这里缺少什么?

__weak typeof(self) weakSelf = self;

_tipSearchController.searchResultBlock = ^(NSArray *tips, BOOL firstBatch) {
    weakSelf.noLocationsAfterSearchFilters = NO;
    if (firstBatch==YES) {
        [weakSelf.tips removeAllObjects]; // empty datasource if required
        [weakSelf.tableView reloadData];
    }

    NSUInteger currentTipCount=weakSelf.tips.count;
    [weakSelf.tips addObjectsFromArray:tips]; // adding data to datasource.

    NSMutableArray *indexPaths = [NSMutableArray array];
    for (NSUInteger i = 0; i < tips.count; ++i) {
        [indexPaths addObject:[NSIndexPath indexPathForRow:i+currentTipCount inSection:0]];
    }

    // Crash here ;(
    [weakSelf.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

};


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tips.count;
}

1 个答案:

答案 0 :(得分:0)

首先,确保在@ mbo42提到的主线程上执行searchResultBlock。 其次,在beginUpdates / endUpdates中包装行插入:

[weakSelf.tableView beginUpdates];
NSUInteger currentTipCount=weakSelf.tips.count;
[weakSelf.tips addObjectsFromArray:tips]; // adding data to datasource.

NSMutableArray *indexPaths = [NSMutableArray array];
for (NSUInteger i = 0; i < tips.count; ++i) {
    [indexPaths addObject:[NSIndexPath indexPathForRow:i+currentTipCount inSection:0]];
}

[weakSelf.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
[weakSelf.tableView endUpdates];