您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發中多線程的五種實現方式與圖片異步加載實踐

編輯:iOS 開發綜合

在 iOS 開發裡,多線程是提升使用者體驗、避免主線程卡頓的關鍵手段。本文整理了五種常見的開啟線程方式,並以「網絡圖片異步加載」為例,示範如何把耗時任務放到子線程,完成後再回到主線程刷新介面。

一、五種開啟多線程的方式

方法一:使用 NSThread 的初始化方法

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(_update) object:nil];

方法二:使用 detachNewThreadSelector 分離線程

[NSThread detachNewThreadSelector:@selector(_update) toTarget:self withObject:nil];

方法三:使用 performSelectorInBackground 在後台執行

[self performSelectorInBackground:@selector(_update) withObject:nil];

方法四:使用 NSOperationQueue 加入區塊任務

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
    for (int i = 0; i < 50; i++) {
        printf("子線程\n");
    }
}];

方法五:透過線程池與 NSInvocationOperation 排程

// 第一步:開啟線程池
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

這樣一來,圖片的下載在背景線程完成,而介面更新則交還主線程處理,既保證了流暢度,也避免了線程安全問題。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved