從網路下載圖片並顯示在 UIImageView 上,是每個 iOS 開發者都會遇到的需求。這裡示範四種實作方式,並說明它們在效能上的差距。
#import "ViewController.h"
#import "UIImage+WebCache.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
imageArray = [NSMutableArray array];
// 建立 5 × 6 的圖片網格
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 6; j++)
{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(j * 65 + 5, i * 64 + 10, 60, 60)];
imageView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:imageView];
[imageArray addObject:imageView];
}
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(160, 400, 80, 30);
[button setTitle:@"載入" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)buttonAction
{
for (UIImageView *imageView in imageArray)
{
NSString *string = @"https://img3.douban.com/view/photo/photo/public/p2221339563.jpg";
NSURL *url = [NSURL URLWithString:string];
[imageView setImageWithURL:url];
}
}
@end
#import@interface UIImageView (WebCache) - (void)setImageWithURL:(NSURL *)url; @end
#import "UIImage+WebCache.h"
@implementation UIImageView (WebCache)
- (void)setImageWithURL:(NSURL *)url
{
// ---------- 第一種:同步載入 ----------
/*
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[self setImage:image];
*/
// ---------- 第二種:NSThread ----------
// NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadImage:) object:url];
// [thread start];
// ---------- 第三種:NSOperationQueue ----------
/*
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 回到主線程修改 UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self setImage:image];
}];
}];
[queue addOperation:op];
*/
// ---------- 第四種:GCD(推薦) ----------
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^{
// 在背景佇列下載
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 回到主線程更新 UI
dispatch_async(dispatch_get_main_queue(), ^{
[self setImage:image];
});
});
}
- (void)loadImage:(NSURL *)url
{
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[self setImage:image];
}
@end
同步載入:程式碼最短,但 dataWithContentsOfURL: 會阻塞呼叫線程。若在主線程呼叫,網路延遲期間整個 UI 會凍結,使用者操作完全無反應。這是不能用在正式產品的寫法。
NSThread:把下載移到背景線程,UI 不再卡住,但 NSThread 需要自己管理生命週期,且沒有取消、暫停、併發數控制等能力,管理大量圖片時很快就不敷使用。
NSOperationQueue:提供操作隊列,可以設定最大併發數、相依性,也支援取消。程式碼比 GCD 冗長一些,但結構清楚,適合有複雜排程需求的場景。
GCD:程式碼最簡潔,效能表現優異,是目前的主流選擇。
上面的範例示範了基本機制,卻缺少所有產品級功能:
實務上請直接使用 SDWebImage 或 Kingfisher 這類成熟套件,一行就能搞定,並內建記憶體與磁碟雙層快取:
[imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
本文的四種寫法適合用來理解底層機制,以及面試時說明你為什麼選擇某個套件。