我尝试异步设置UITableViewCell
“描述”字段,但由于重用视图单元格,我在快速滚动我的表格视图时遇到问题 - 表格视图单元格被刷新了几次。我的代码如下。这里有什么问题?
- (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;
}