2013-02-27 65 views
1

以下两种从URL中获取UIImage的方法之间的主要区别是什么?我最近从方法1转换方法2在我的应用程序中,似乎经历了速度的急剧增加,当我认为,实质上,两种方法在实践中几乎相同。试图弄清楚为什么我看到这样的速度增加。从URL获取图像的两种方法:区别?

方法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

我最好的猜测是,因为方法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,实际上只是一些方法的集合,更像是事务处理。

可能还有更多。

+0

但不是方法2也使用发送异步请求,也就是说,它也会是多线程的? – MikeS 2013-02-27 20:12:23

+1

'dispatch_async()'函数调度用于并发执行的块* [1](https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_async.3.html)。 **方法2中的NSURLConnection符合'NSMutableCopying',所以编译器在运行时间之前做任何提升。 * [2](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html) – user2000809 2013-02-27 20:33:23

+0

嗯,这是一个有趣的理论...... +1 – MikeS 2013-02-27 20:38:25

相关问题