【发布时间】: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