滞后滚动tableview与图像

时间:2016-03-15 20:45:52

标签: ios objective-c uitableview

我将图片添加到我的tableView单元格中,这让它变得迟钝。我仍然是目标c的新手,我不明白是什么导致这个或如何解决它。非常感谢任何帮助!

group[PF_GROUP_LOGO]只是我的数据库中的一个字符串,对每个对象都是唯一的。代码有效,尝试滚动时只是非常滞后。

//-------------------------------------------------------------------------------------------------------------------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];

    PFObject *group = groups[indexPath.row];


    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:group[PF_GROUP_LOGO]]]];
    cell.imageView.image = image;

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d users", (int) [group[PF_GROUP_MEMBERS] count]];
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];


    return cell;
}

1 个答案:

答案 0 :(得分:8)

有很多工具可以帮助你解决这个问题。

在基础级别,问题是您在主线程上运行了一个长进程,这会阻止UI。从非本地URL加载图像非常耗时,您应该在后台线程上执行此操作,因此不会阻止UI。

同样,有很多方法可以做到这一点,我强烈建议您对异步资源加载进行一些研究,但这是您可以在自己的示例范围内做的一件事:

//-------------------------------------------------------------------------------------------------------------------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];

    PFObject *group = groups[indexPath.row];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ // go to a background thread to load the image and not interfere with the UI
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:group[PF_GROUP_LOGO]]]];
        dispatch_async(dispatch_get_main_queue(), ^{ // synchronize back to the main thread to update the UI with your loaded image
            cell.imageView.image = image;
        });
    });

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d users", (int) [group[PF_GROUP_MEMBERS] count]];
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];

    return cell;
}

我还建议使用AFNetworking,因为authorUIImageView之上构建了一个非常好的类别,允许您自动从后台加载网址中的图像。同样,在这个过程中有许多思想流派,这只是一个想法。我建议您阅读this以获取有关该主题的完整教程。

我希望这有用!

相关问题