【问题标题】:UITableView and changing datasource while the table is being renderedUITableView 并在呈现表格时更改数据源
【发布时间】:2014-09-03 09:02:07
【问题描述】:

我有一个带有UITableView 的视图控制器。表格视图的数据源是一个NSArray,正在从网络异步加载。

第一次加载数据时,一切都很好,但由于数据也会不时刷新,我注意到当 UITableView 仍在渲染单元格并因此调用 @987654323 时,我有一个竞速状态@ 而 NSArray 正在被刚刚完成获取新数据的异步操作设置为不同的值。

我相信numberOfRowsInSection 已返回旧 NSArray 的长度,并且 UITableView 正在根据该值呈现单元格。但与此同时,我的 NSArray 已重新加载,并且它的对象更少,因此 cellForRowAtIndexPath 实际上试图索引一个超出数组边界的值。

有没有办法中断单元格的渲染,或者更好的是,知道 UITableView 何时完成单元格的渲染,以便我可以更新数据源?

有没有其他方法可以解决这类问题?

更新:我添加了示例代码

代表们:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return [_rootCategories count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    NSString *CellIdentifier = @"RootCell";
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[ALTRootCategoryCell alloc] init];
    }
    ALTRootCategoryCell *rcc = (ALTRootCategoryCell *)cell;
    ALTRootCategory *rc = [_rootCategories objectAtIndex:indexPath.row];
    NSString *s = [NSString stringWithFormat:@"%@ (%d punti)", rc.title, [rc.valueMax intValue]];
    rcc.title.text = s;
    return cell;
}

执行异步获取的代码几乎是这样的:

[[ALTWebService sharedInstance] rootCategory:^(NSArray *result) {
    _rootCategories = [[ALTWebService sharedInstance] fetchRootCategories];
    dispatch_async(dispatch_get_main_queue(), ^{
        [_mainTable reloadData];
        [[ALTNotificationManager sharedInstance] manageSavedNotification];
    });
} failure:^(NSString *error) {
    [ALTAlert dismiss];
    [ALTAlert error:error];
    hasErrors = YES;
}];

【问题讨论】:

  • @mehulpatel 是的,但是如果我更改 NSArray 并假设旧的有 5 个项目而新的只有 3 个,如果它仍然呈现 5,我将得到数组越界异常来自前一个数组的单元格。

标签: ios uitableview nsarray


【解决方案1】:

更改DataSource后应调用reloadData方法更新表:

[self.tableView reloadData];

【讨论】:

  • 我已经这样做了,但是在调用 reloadData 之前数组被重新分配。
  • @ValerioSantinelli 可能您在虚拟化方面遇到了一些问题。您是否覆盖了 ALTRootCategoryCell 中的 -prepareForReuse?
  • 不,我没有覆盖prepareForReuse。该单元格唯一的特殊之处在于它包含一个UICollectionView,但即使只有一个UILabel 的单元格也会出现此问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
相关资源
最近更新 更多