NSThread 简介
NSThread 是苹果官方提供的面向对象类线程操作技术,简单方便,可以直接操作线程对象,不过需要自己控制线程的生命周期,在平时使用较少。
开启线程
使用 NSThread 开启线程有类方法和实例方法两种,类方法会直接执行任务,实例方法需要在实例初始化后调用 start 方法才能开始执行任务。
类方法创建线程
使用类方法创建线程后会自动开始任务,不需要手动开启。类方法创建线程有如下两种方式:
// block 方式
+ (void)detachNewThreadWithBlock:(void (^)(void))block;
// SEL 方式
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
block 方式:
[NSThread detachNewThreadWithBlock:^{
NSLog(@"class method -- task in block, current thread is %@", [NSThread currentThread]);
}];
// 执行后打印:class method -- task in block, current thread is <NSThread: 0x6000022f2300>{number = 4, name = (null)}
SEL 方式:
[NSThread detachNewThreadSelector:@selector(classMethodTest) toTarget:self withObject:nil];
- (void)classMethodTest {
NSLog(@"class method -- task in SEL, current thread is %@", [NSThread currentThread]);
}
// 执行后打印:class method -- task in SEL, current thread is <NSThread: 0x6000022e76c0>{number = 3, name = (null)}
实例方法创建线程
实例方法创建线程也是分为 block 和 SEL 两种方式:
// block 方式
- (instancetype)initWithBlock:(void (^)(void))block;
// SEL 方式
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument;
block 方式:
// 1. 创建线程
NSThread *oneThread = [[NSThread alloc] initWithBlock:^{