我有UITableView
。在tableView:cellForRow:atIndexPath:
方法中(当数据填充到单元格时)我实现了某种延迟加载。如果程序在后台rowData
NSDictionary
启动方法中没有 key(key==row number) 的对象。requestDataForRow:
所以在单元格变得可见后,单元格中的数据会被填充一点。这是代码:
static int requestCounter=0;
-(void)requestDataForRow:(NSNumber *)rowIndex
{
requestCounter++;
//NSLog(@"requestDataForRow: %i", [rowIndex intValue]);
PipeListHeavyCellData *cellData=[Database pipeListHeavyCellDataWithJobID:self.jobID andDatabaseIndex:rowIndex];
[rowData setObject:cellData forKey:[NSString stringWithFormat:@"%i", [rowIndex intValue]]];
requestCounter--;
NSLog(@"cellData.number: %@", cellData.number);
if (requestCounter==0)
{
//NSLog(@"reloading pipe table view...");
[self.pipeTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
};
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"pipeCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
[[NSBundle mainBundle] loadNibNamed:@"PipesForJobCell" owner:self options:nil];
cell = pipeCell;
self.pipeCell = nil;
PipeListHeavyCellData *cellData=[[PipeListHeavyCellData alloc] init];
if ([rowData objectForKey:[NSString stringWithFormat:@"%i", indexPath.row]]==nil)
{
//NSLog(@" nil data for row: %i", indexPath.row);
[self performSelectorInBackground:@selector(requestDataForRow:) withObject:[NSNumber numberWithInt:indexPath.row]];
}
else
{
//NSLog(@" has data for row: %i", indexPath.row);
PipeListHeavyCellData *heavyData=[[PipeListHeavyCellData alloc] init];
heavyData=(PipeListHeavyCellData *)[rowData objectForKey:[NSString stringWithFormat:@"%i", indexPath.row]];
cellData._id=[heavyData._id copy];
cellData.number=[heavyData.number copy];
cellData.status=[heavyData.status copy];
};
此代码有效,一切正常,但我的表有 2000 行,如果用户从索引为 10 的单元格快速滚动到索引为 2000 的单元格。他必须等待很长时间,直到所有拉取数据请求都完成(对于第 11、12、13、...、2000 行),因为在用户滚动表格视图时行变得可见,因此requestDataForRow
为它们调用了该方法。
我怎样才能优化这些东西?