3

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

哪个更有效率?更优雅?更安全?等等

- (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];
         }
     }];
}

或者

- (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];
            }
        });
    });
}
4

2 回答 2

1

所以我为我自己的问题想出了一个答案:
目前有 3 种主要方法可以异步加载图像。

  1. NSURL连接
  2. GCD
  3. NSOperationQueue

对于每个问题,选择最好的方法都是不同的。
例如,在 a 中UITableViewController,我将使用第三个选项 ( NSOperationQueue) 为每个单元格加载图像,并确保在分配图片之前该单元格仍然可见。如果单元格不再可见,则应取消该操作,如果 VC 从堆栈中弹出,则应取消整个队列。

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

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

于 2013-02-01T20:51:54.630 回答
0

sendAsynchronousRequest更好,更优雅,随便你怎么称呼。但是,就个人而言,我更喜欢单独创建NSURLConnection并听取其delegatedataDelegate方法。这样,我可以: 1. 设置我的请求超时。2. 使用 的缓存机制设置要缓存的图像NSURLRequest(虽然不可靠)。2. 观看下载进度。3.NSURLResponse在实际下载开始之前接收(对于 http 代码 > 400)。等等......而且,它还取决于图像大小和应用程序的其他一些要求等情况。祝你好运!

于 2012-10-26T08:13:02.967 回答