Tôi có UITableView
. theo phương pháp tableView:cellForRow:atIndexPath:
(khi dữ liệu được điền vào ô) Tôi đã triển khai một số loại tải chậm. Nếu không có đối tượng cho khóa (key == số hàng) trong rowData
NSDictionary
, chương trình sẽ khởi chạy phương thức requestDataForRow:
ở chế độ nền. do đó, dữ liệu trong các ô được điền một chút sau khi ô hiển thị. Dưới đây là các mã:Tối ưu hóa tải tối ưu UITableView
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];
};
Mã này hoạt động, mọi thứ đều OK, NHƯNG bàn của tôi có 2000 hàng và Nếu người dùng cuộn từ tế bào với chỉ số 10 đến ô với chỉ số 2000 rất nhanh chóng. Ông phải chờ một thời gian dài cho đến khi tất cả các yêu cầu dữ liệu kéo sẽ hoàn thành (đối với các hàng 11, 12, 13, ..., 2000) khiến các hàng đó trở nên hiển thị trong khi người dùng đang cuộn chế độ xem bảng để phương pháp requestDataForRow
được gọi cho họ.
Làm cách nào để tối ưu hóa những thứ đó?
Đây là một câu hỏi tuyệt vời với cùng một vấn đề với một số giải pháp rất tốt (với mã): http://stackoverflow.com/q/7567827/937822 – lnafziger