在 iOS 開發裡,多線程是提升使用者體驗、避免主線程卡頓的關鍵手段。本文整理了五種常見的開啟線程方式,並以「網絡圖片異步加載」為例,示範如何把耗時任務放到子線程,完成後再回到主線程刷新介面。
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(_update) object:nil];
[NSThread detachNewThreadSelector:@selector(_update) toTarget:self withObject:nil];
[self performSelectorInBackground:@selector(_update) withObject:nil];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
for (int i = 0; i < 50; i++) {
printf("子線程\n");
}
}];
// 第一步:開啟線程池
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 設置最大並發數目
[queue setMaxConcurrentOperationCount:2];
// 第二步:創建操作並加入線程池
NSInvocationOperation *thread1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update1) object:nil];
NSInvocationOperation *thread2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update2) object:nil];
// 設置操作優先級
[thread1 setQueuePriority:NSOperationQueuePriorityVeryLow];
[thread2 setQueuePriority:NSOperationQueuePriorityVeryHigh];
// 加入隊列
[queue addOperation:thread1];
[queue addOperation:thread2];
網絡圖片的加載往往伴隨延遲,如果在主線程同步下載,會直接阻塞介面渲染,造成掉幀甚至卡死。合理的做法是把下載任務放到子線程執行,待圖片準備好後,再切回主線程更新 UI。
透過為 UIImageView 增加類別(Category),封裝一套可複用的異步下載方法。核心代碼如下:
#import "UIImageView+thread.h"
@implementation UIImageView (load)
- (void)setImageWithUrl:(NSString *)url {
[self performSelectorInBackground:@selector(_loadImage:) withObject:url];
}
- (void)_loadImage:(NSString *)u {
@autoreleasepool {
NSURL *url = [NSURL URLWithString:u];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 回到主線程更新介面
[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
}
}
@end
這樣一來,圖片的下載在背景線程完成,而介面更新則交還主線程處理,既保證了流暢度,也避免了線程安全問題。