从URL获取图像的两种方法:差异?

时间:2013-02-27 18:55:18

标签: objective-c uiimage nsurlconnection nsdata

以下两种从URL获取UIImage的方法有哪些主要区别?我最近在我的应用程序中将从方法1 切换到方法2 ,并且当我认为这两种方法在实践中几乎相同时,似乎经历了速度的急剧增加。只是想弄清楚为什么我看到这样的速度增加。

方法1

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    NSData *imageData = [NSData dataWithContentsOfURL:self.imageURL];

    dispatch_async(dispatch_get_main_queue(), ^{
        self.image = [UIImage imageWithData:imageData];
    });
});

方法2

- (void)fetchImage
{
    NSURLRequest *request = [NSURLRequest requestWithURL:self.imageURL];
    self.imageData = [[NSMutableData alloc] init];
    self.imageURLConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}   

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if(connection == self.imageURLConnection)
    {
        [self.imageData appendData:data];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if(connection == self.imageURLConnection)
    {
        self.image = [UIImage imageWithData:self.imageData];
    }
}

1 个答案:

答案 0 :(得分:1)

我最好的猜测是因为方法1 AsyncURLConnection类多线程:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    /* process downloaded data in Concurrent Queue */

    dispatch_async(dispatch_get_main_queue(), ^{

        /* update UI on Main Thread */

因此,由于争用共享资源,您可能会看到性能下降。

另一方面,方法2 ,实际上只是一组方法,它们的实现更像是事务处理。

可能还有更多内容。

相关问题