在UITableView中从Web加载图像的更有效方法是什么?

时间:2015-02-16 23:12:33

标签: ios objective-c uitableview

对于UITableViewCell中的每个UITableView,我在后台线程中从网上下载了一张图片。然后我使用主线程从单元格更新imageView。

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
                //Background Thread
                // download the image in separate thread
                UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: @"someurl.com" ] ] ];
                dispatch_async(dispatch_get_main_queue(), ^(void){
                    // this is called in the main thread after the download has finished, here u update the cell's imageView with the new image
                    cell.eventImageView.image = image;
                });
            });

滚动时我没有注意到任何滞后。

但是,我想知道是否有更好的方法可以做到这一点,如果有的话,我该怎么办呢?

由于

1 个答案:

答案 0 :(得分:3)

我更喜欢使用SDWebImage(can be found here on Git

我写的页面听起来与你的相似,而且代码非常简单:

    // Set and load the images
    [cell.menuImageView sd_setImageWithURL:url placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

        // Get rid of the activity indicator when the image has been loaded
        [activity stopAnimating];
    }];

在我看来,有许多优点:

1)图书馆很灵活,为您提供了许多关于如何下载图像的选项(这些只是少数几个)

例如:

- (void)sd_setImageWithURL:(NSURL *)url
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options
- (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock

2)图书馆缓存图片意味着下次您不必再次下载图片。

3)图书馆得到了很好的支持,有助于解决问题

我个人开始使用您使用的技术,发现存在局限性和困难(如果图像下载速度慢等添加活动指示器等),然后试用了许多不同的异步图像下载器,这个是最好的

希望有所帮助