本文介绍了加载远程图像的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究,但没有找到这个问题的任何答案 - sendAsynchronousRequest vs. dataWithContentsOfURL。

I've been researching and haven't found any answer to this question - sendAsynchronousRequest vs. dataWithContentsOfURL.

哪个更有效?更优雅?更安全吗?等等。

Which is more efficient? more elegant? safer? etc.

- (void)loadImageForURLString:(NSString *)imageUrl
{
    self.image = nil;

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
     {
         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
         if (data) {
             self.image = [UIImage imageWithData:data];
         }
     }];
}

OR

- (void)loadRemoteImage
{
    self.image = nil;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSData * imageData = [NSData dataWithContentsOfURL:self.URL];
        if (imageData)
            self.image = [UIImage imageWithData:imageData];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.image) {
                [self setupImageView];
            }
        });
    });
}


推荐答案

所以我来了回答我自己的问题:

目前有3种主要方法可以加载图像异步。

So I've come up with an answer for my own question:
Currently there are 3 main ways to load images async.


  1. NSURLConnection

  2. GCD

  3. NSOperationQueue

选择每个问题的最佳方式都不同。

例如,在 UITableViewController 中,我会使用第3个选项( NSOperationQueue )为每个单元格加载图像,并确保在分配图片之前单元格仍然可见。如果单元格不再可见,则应该取消该操作,如果VC从堆栈中弹出,则应取消整个队列。


使用 NSURLConnection时 + GCD我们没有取消选项,因此应该在不需要时使用(例如,加载一个恒定的背景图像)。


另一个好建议是将图像存储在缓存中,即使它不再显示,也可以在启动另一个加载过程之前在缓存中查找。

Choosing the best way is different for every problem.
For example, in a UITableViewController, I would use the 3rd option (NSOperationQueue) to load an image for every cell and make sure the cell is still visible before assigning the picture. If the cell is not visible anymore that operation should be cancelled, if the VC is popped out of stack then the whole queue should be cancelled.

When using NSURLConnection + GCD we have no option to cancel, therefore this should be used when there is no need for that (for example, loading a constant background image).

Another good advice is to store that image in a cache, even it's no longer displayed, and look it up in cache before launching another loading process.

这篇关于加载远程图像的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:41