MST

星途 面试题库

面试题:Objective-C中NSThread类如何创建并启动一个新线程?

请描述使用Objective-C的NSThread类创建并启动一个新线程的具体步骤,并给出相应的代码示例。
23.1万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 创建线程对象:使用NSThread类的类方法initWithTarget:selector:object:创建一个线程对象,其中target是线程执行的对象,selector是线程要执行的方法,object是传递给该方法的参数。
  2. 启动线程:调用线程对象的start方法启动线程。

以下是代码示例:

#import <Foundation/Foundation.h>

// 线程执行的方法
- (void)threadTask:(NSString *)message {
    NSLog(@"线程开始执行,参数: %@", message);
    // 模拟一些耗时操作
    for (int i = 0; i < 5; i++) {
        NSLog(@"线程正在执行: %d", i);
        [NSThread sleepForTimeInterval:1];
    }
    NSLog(@"线程执行完毕");
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 创建线程对象
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadTask:) object:@"Hello, Thread!"];
        // 启动线程
        [thread start];
        
        NSLog(@"主线程继续执行");
    }
    return 0;
}