从URL加载的UITableView图像出现奇怪的线程问题

时间:2014-11-11 13:12:30

标签: ios objective-c xcode uitableview lazy-loading

首先我是一名UI设计师进入Xcode,所以如果我在这里的描述中有点模糊,请耐心等待。

基本上我有一个UITableView充满了联系人,每个联系人都有一个照片图像在名称的左边,通过网址从网络中提取..我已经实现了延迟加载图像,但滚动列表时,我似乎变得奇怪的闪烁和一个真正的“迟钝”#39; (即不顺利)滚动。

我尝试过使用setNeedsDisplay电话(我知道其中有很多电话),但它似乎仍然无法解决。

一直试图谷歌一些最佳实践'为此,但不确定这里发生了什么......任何帮助将不胜感激!谢谢。

目标:Xcode 6.1中的iOS8

这是我的cellForRowAtIndexPath代码:

if([peep getImage].length > 4) // if URL smaller than 4, it's probably not a valid URL
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if([peep getImage])
        {
            if(![imageCache objectForKey:indexPath])
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[peep getImage]]]];
                    if(image != nil) {
                        [imageCache setObject:image forKey:indexPath];
                        [cell.peepImage setImage:[imageCache objectForKey:indexPath]];
                        [[cell peepImage] setNeedsDisplay];
                    }
                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[cell peepImage] setImage:[imageCache objectForKey:indexPath]];
                    [[cell peepImage] setNeedsDisplay];
                });
            }
        }
        [cell.peepImage setNeedsDisplay];
    });
}
else
{
    cell.peepImage.image = [UIImage imageNamed: @"defaultuser.jpg"];
}
[cell setNeedsDisplay];
return cell;

}

1 个答案:

答案 0 :(得分:0)

我的猜测是在主线程上创建图像。通过将其从主线程移开,您的问题应该得到解决。

if([peep getImage].length > 4) // if URL smaller than 4, it's probably not a valid URL
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if([peep getImage])
        {
            if(![imageCache objectForKey:indexPath])
            {
                // Move image creation here
                __block UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[peep getImage]]]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(image != nil) {
                        [imageCache setObject:image forKey:indexPath];
                        [cell.peepImage setImage:[imageCache objectForKey:indexPath]];
                        [[cell peepImage] setNeedsDisplay];
                    }
                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[cell peepImage] setImage:[imageCache objectForKey:indexPath]];
                    [[cell peepImage] setNeedsDisplay];
                });
            }
        }
        [cell.peepImage setNeedsDisplay];
    });
}
else
{
    cell.peepImage.image = [UIImage imageNamed: @"defaultuser.jpg"];
}
[cell setNeedsDisplay];
return cell;