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