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

實例解析 iOS 多執行緒開發中 NSThread 類的用法

編輯:iOS 開發綜合

NSThread 是蘋果提供的執行緒操作類別,相較於 GCD 與 NSOperation,它更為輕量、也更直觀,適合需要精細控制執行緒的場景。本文將從初始化、執行緒操作、執行緒間通訊,到一個完整的圖片下載範例,全面解析 NSThread 的用法。

一、NSThread 的初始化

1. 動態方法

透過 initWithTarget:selector:object: 建立執行緒,設定優先級後呼叫 start 啟動:

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
thread.threadPriority = 1;  // 優先級 0.0 - 1.0,1.0 最高
[thread start];

參數說明:selector 是執行緒要執行的辦法(最多接收一個參數);target 是 selector 的發送對象;argument 是傳給 selector 的參數,可為 nil。

2. 靜態方法

使用 detachNewThreadSelector:toTarget:withObject: 會在呼叫後立即建立並開啟新執行緒:

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

3. 隱式建立

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

二、獲取與暫停執行緒

NSThread *current = [NSThread currentThread]; // 獲取當前執行緒
NSThread *main    = [NSThread mainThread];    // 獲取主執行緒

[NSThread sleepForTimeInterval:2];            // 暫停 2 秒

三、執行緒間的通訊

執行緒通訊是多執行緒開發的關鍵環節,NSThread 提供了幾種便捷方法:

// 在指定執行緒上執行操作
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];

// 在主執行緒上執行操作(常用於更新 UI)
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];

四、優缺點

優點:NSThread 比其他兩種方案更輕量級,能更直觀地控制執行緒物件。
缺點:需要自己管理執行緒的生命週期與同步問題,而執行緒同步時對資料加鎖會帶來一定的系統開銷。

五、完整範例:非同步下載圖片

以下範例示範如何在子執行緒下載圖片,再回到主執行緒更新 UI——這是 iOS 開發中最典型的多執行緒應用場景。

#define kURL @"https://avatar.csdn.net/2/C/D/1_totogo2010.jpg"

@implementation ViewController

- (void)downloadImage:(NSString *)url {
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
    UIImage *image = [[UIImage alloc] initWithData:data];
    if (image != nil) {
        // 下載完成後回主執行緒更新 UI
        [self performSelectorOnMainThread:@selector(updateUI:)
                              withObject:image waitUntilDone:YES];
    }
}

- (void)updateUI:(UIImage *)image {
    self.imageView.image = image;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 建立並啟動子執行緒下載圖片
    NSThread *thread = [[NSThread alloc] initWithTarget:self
                                              selector:@selector(downloadImage:)
                                                object:kURL];
    [thread start];
}
@end

這個範例清楚展示了 NSThread 的核心價值:把耗時的網路請求放到子執行緒,避免阻塞主執行緒導致界面卡頓;下載完成後,再透過 performSelectorOnMainThread: 安全地回到主執行緒更新 UI。掌握 NSThread 的这些基础用法,你就能在多執行緒場景中做出更靈活精細的控制。

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