Saturday, 10 August 2013

correct way to asynchronously load tableview cell data

correct way to asynchronously load tableview cell data

I try to asynchronously set tableview cell 'desciption' field, but due to
reusing view cells I have problems when fast scroll my tableview -
tableview cells are refreshed several times. My code is below. What's
wrong here?
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
[TimeExecutionTracker
startTrackingWithName:@"cellForRowAtIndexPath"];
static NSString *CellIdentifier = @"MessageCell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
CTCoreMessage *message = [_searchResults
objectAtIndex:indexPath.row];
UILabel *fromLabel = (UILabel *)[cell viewWithTag:101];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:102];
UILabel *subjectLabel = (UILabel *)[cell viewWithTag:103];
UILabel *descriptionLabel = (UILabel *)[cell viewWithTag:104];
[subjectLabel setText:message.subject];
[fromLabel setText:[message.from toStringSeparatingByComma]];
[dateLabel setText:[NSDateFormatter
localizedStringFromDate:message.senderDate
dateStyle:NSDateFormatterShortStyle
timeStyle:nil]];
NSString *cellHash = [[NSString
stringWithFormat:@"%@%@%@",fromLabel.text,dateLabel.text,subjectLabel.text]
md5];
if([_tableViewDescirptions valueForKey:cellHash] == nil){
[descriptionLabel setText:@"Loading ..."];
dispatch_async(backgroundQueue, ^{
BOOL isHTML;
NSString *shortBody = [message
bodyPreferringPlainText:&isHTML];
shortBody = [shortBody substringToIndex: MIN(100,
[shortBody length])];
[_tableViewDescirptions setValue:shortBody forKey:cellHash];
dispatch_async(dispatch_get_main_queue(), ^{
[descriptionLabel setText:[_tableViewDescirptions
valueForKey:cellHash]];
});
});
}else{
[descriptionLabel setText:[_tableViewDescirptions
valueForKey:cellHash]];
}
[TimeExecutionTracker stopTrackingAndPrint];
return cell;
}

No comments:

Post a Comment