UITableView滚动从服务器加载图像时冻结

时间:2013-03-17 08:17:28

标签: ios objective-c cocoa-touch

我正在使用此代码在使用自定义单元格的UITableView中加载我的图像

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

static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    for (id currentObject in topLevelObjects) {
        if ([currentObject isKindOfClass:[CustomCell class]]) {
            cell = (CustomCell *) currentObject;
            break;
        }
    }

    NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
    NSURL *imageURL = [NSURL URLWithString:tempString];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
    cell.img.image = image;

}

return cell;
}

使用上面的代码,上下滚动没有问题,但是图像没有正确显示,一些图像在表格中重复,例如,如果数组保存10个图像,从1到10,数组在顺序上是正确的,我在表中得到的图像类似于1,2,3,4,3,3,1,10,8,9

但是当我使用这段代码时

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

static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    for (id currentObject in topLevelObjects) {
        if ([currentObject isKindOfClass:[CustomCell class]]) {
            cell = (CustomCell *) currentObject;
            break;
        }
    }

}

NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
    NSURL *imageURL = [NSURL URLWithString:tempString];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
    cell.img.image = image;

return cell;
}

图像排序很好,没有重复但是当我滚动到表格的底部然后滚动回到顶部表格冻结2或3秒

任何想法如何解决这个问题?

数组包含 http://www.website.com/image.jpg

等图片的链接

自定义单元格包含IBOutlet UIImageView 60x60,从服务器加载的图像也是60x60

1 个答案:

答案 0 :(得分:8)

尝试使用以下代码在线程中下载图像。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
    NSURL *imageURL = [NSURL URLWithString:tempString];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
    dispatch_async(dispatch_get_main_queue(), ^{
      cell.img.image = image;
    });
});