将UITableViewCell重用于GCD [英] Reusing UITableViewCell with GCD

查看:83
本文介绍了将UITableViewCell重用于GCD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Grand Central Dispatch 以异步方式加载 UITableViewCell 的图像。这种方法很有效,除了在一些重复使用单元格的边框情况下,前一个块加载了错误的图像。

I'm using Grand Central Dispatch to load images of a UITableViewCell asynchronously. This works well except in some border cases in which the cell is reused, and a previous block loads the wrong image.

我当前的代码如下所示:

My current code looks like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    NSString *imagePath = [self imagePathForIndexPath:indexPath];         
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

    dispatch_async(queue, ^{
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

        dispatch_sync(dispatch_get_main_queue(), ^{
            cell.imageView.image = image;
            [cell setNeedsLayout];
        });
    });

    return cell;
}

据我所知,GCD队列无法停止。那么如何防止这种边界情况呢?或者我应该使用其他东西而不是GCD来解决这个问题?

As far as I know GCD queues cannot be stopped. How can this border case be prevented then? Or should I be using something else instead of GCD to solve this problem?

推荐答案

我所做的是添加 NSOperation ivar到单元格。该操作负责获取,加载和创建映像。完成后,它会ping细胞。当/如果单元格出列时,操作将被取消并在未完成时销毁。在 -main 中取消的操作测试。将图像传递到单元格后,单元格将删除操作并使用图像。

what i've done is added an NSOperation ivar to the cell. the operation is responsible for getting, loading, and creating the image. when completed, it pings the cell. when/if the cell is dequeued, the operation is cancelled and destroyed if it has not finished. the operation test for cancellation when in -main. after the image is passed to the cell, the cell drops the operation and uses the image.

这篇关于将UITableViewCell重用于GCD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆