正确加载tableview单元格数据的正确方法

时间:2013-08-10 08:38:39

标签: iphone ios objective-c uitableview

我尝试异步设置UITableViewCell'description'字段,但是由于重用视图单元格,我在快速滚动我的tableview时遇到问题 - tableview单元格被刷新了好几次。我的代码如下。这有什么不对?

   - (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;
    }

4 个答案:

答案 0 :(得分:5)

dispatch_async(dispatch_get_main_queue(), ^{
    [descriptionLabel setText:[_tableViewDescirptions valueForKey:cellHash]];
});

捕获 descriptionLabel的当前值,因此,当...时 执行块,即使该单元格已被重复使用,也会更新该标签 在此期间的索引路径。

因此,您应该捕获单元格,并检查单元格(当前)索引路径是否仍然等于原始(捕获)索引路径。

您还应该仅在主线程上更新_tableViewDescirptions 用作数据源

这大致看起来像(不是经过编译器测试):

dispatch_async(dispatch_get_main_queue(), ^{
    [_tableViewDescirptions setValue:shortBody forKey:cellHash];
    if ([[tableView indexPathForCell:cell] isEqual:indexPath]) {
        UILabel *descriptionLabel = (UILabel *)[cell viewWithTag:104];
        [descriptionLabel setText:[_tableViewDescirptions valueForKey:cellHash]];
    }
});

附注:获取/设置字典值的主要方法是objectForKeysetObject:forKey:valueForKey:setValue:forKey:仅用于键值编码魔术。

答案 1 :(得分:2)

我找到了一个优雅的解决方案,只需3步(来自http://developer.apple.com/library/ios/samplecode/LazyTableImages/Introduction/Intro.html):

 // 1. Create a method for asynch. downloading tableview cell data:

    - (void) loadMessageDescription:(CTCoreMessage *)message forIndexPath:(NSIndexPath *)indexPath
    {
        dispatch_async(backgroundQueue, ^{

            BOOL isHTML;
            NSString *shortBody = [message bodyPreferringPlainText:&isHTML];
            shortBody = [shortBody substringToIndex: MIN(100, [shortBody length])];

            dispatch_async(dispatch_get_main_queue(), ^{

                UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

                [_messagesDescriptions setValue:shortBody forKey:[NSString stringWithFormat:@"%d",message.hash]];
                [(UILabel *)[cell viewWithTag:104] setText:shortBody];
                //[cell setNeedsLayout];
            });
        });
    }

//2. check for the tableview scrolling when get a tableview cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{

...

if (_tableView.dragging == NO && _tableView.decelerating == NO){

            [self loadMessageDescription:message forIndexPath:indexPath];
        }

...

// 3. When the scroll stopped - load only visible cells

- (void)loadMessageDescriptionForOnscreenRows
{
    NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
    for (NSIndexPath *indexPath in visiblePaths)
    {
        CTCoreMessage *message = [_searchResults objectAtIndex:indexPath.row];

        if([_messagesDescriptions valueForKey:[NSString stringWithFormat:@"%d",message.hash]] == nil){
            {
                [self loadMessageDescription:message forIndexPath:indexPath];
            }
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate){

        [self loadMessageDescriptionForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadMessageDescriptionForOnscreenRows];
}

答案 2 :(得分:1)

我认为问题在于,当异步处理完成并成功时,您只填写_tableViewDescirptions(有趣名称BTW)字典。因此,当单元格快速滚动时,您将反复设置大量异步调用。

相反,请始终立即设置说明(例如,使用“正在加载...”)并仅执行一次后台任务。下次调用此方法时,它不会尝试另一次下载。当然,如果下载失败,您需要回退。

此外,我认为不是构建昂贵的字符串哈希,而是可以使用indexPath作为密钥。

最后,在我看来,你在后台任务中所做的工作是微不足道的,可以很容易地在主线程中完成。

答案 3 :(得分:-2)

在您按照我的回答之前,我想告诉您,以下代码对内存管理不利,因为它会为UITableView的每一行创建新单元格,所以要小心。

但最好使用,当UITableView有限行(约50-100可能)时,以下代码对您的情况有帮助。如果它适合你,请使用它。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *CellIdentifier = [NSString stringWithFormat:@"S%1dR%1d",indexPath.section,indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

         /// Put your code here.
     }

      /// Put your code here.

    return cell;
}

如果您的行数有限,那么这是最好的代码。

相关问题