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];
}
}
但不是方法2也使用发送异步请求,也就是说,它也会是多线程的? – MikeS 2013-02-27 20:12:23
'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
嗯,这是一个有趣的理论...... +1 – MikeS 2013-02-27 20:38:25