使用SDWebImage时表视图滚动滞后

Adr*_*ian 7 ios sdwebimage

我正在里面的桌面视图中加载一些来自互联网的图像cellForRowAtIndexPath.这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"ArticleCell";
    ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    Article *article = [parser items][indexPath.row];

    cell.title.text = article.title;
    cell.newsDescription.text = article.description;
    [cell.image setImageWithURL:[NSURL URLWithString:article.image]];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,即使我使用SDWebImage,当我向下滚动时,我的应用程序仍然滞后.以下是一些截图Instruments:

在此输入图像描述

在此输入图像描述

The*_*ude 5

看起来即使在后台线程中执行图像下载,图像数据的工作也在主线程中完成,因此它会阻止您的应用程序.您可以尝试SDWebImage提供的异步图像下载程序.

[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
                                                    options:0
                                                   progress:^(NSUInteger receivedSize, long long expectedSize)
                                                   {
                                                       // progression tracking code
                                                   }
                                                   completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
                                                   {
                                                       if (image && finished)
                                                       {
                                                           // do something with image
                                                       }
                                                   }
];
Run Code Online (Sandbox Code Playgroud)

在你的方法中它应该看起来像:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"ArticleCell";
    ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    Article *article = [parser items][indexPath.row];

    cell.title.text = article.title;
    cell.tag = indexPath.row;
    cell.newsDescription.text = article.description;
    [SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
                                                        options:0
                                                       progress:nil
                                                      completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
     {
         if (cell.tag == indexPath.row && image && finished)
         {
            dispatch_async(dispatch_get_main_queue(), ^(){
               cell.image = image;
            });

         }
     }];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)