iOS 使用NSThread来代表线程,创建新线程也就是创建一个NSThread对象。
1 创建和启动线程
在iOS10之前提供了两种方法开启线程。
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument NS_AVAILABLE(10_5, 2_0);
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
第一种方法是实例方法,返回一个NSThread对象,必须调用start方法来启动线程。
第二种方法是类方法,不会返回NSThread对象,直接创建并启动线程。
iOS10增加了两种创建启动线程的方法
- (instancetype)initWithBlock:(void (^)(void))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
+ (void)detachNewThreadWithBlock:(void (^)(void))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
这两个方法与上述类似,也是一个实例方法,一个类方法。只是执行方法体不一样了。具体使用如下:
#import "ZPYViewController.h"
@interface ZPYViewController ()
@end
@implementation ZPYViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self makeThread1beforeIOS10];
[self makeThread2beforeIOS10];
[self makeThread1FromIOS10];
[self makeThread2FromIOS10];
}
-(void)run{
for(int i=0;i<10;i++){
NSLog(@"%@,----i=%d",[NSThread currentThread],i);
NSLog(@"isMainThread=%d",[NSThread isMainThread]);
}
}
//iOS 10 之前NSThread两种方法创建线程。如下:
-(void) makeThread1beforeIOS10{
//第一种创建方式 实例方法 最多可以传一个参数
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread1 setName:@"fisrt blood"];
//启动线程
[thread1 start];
BOOL isMain = [NSThread isMainThread];
NSLog(@"isMain=%d,thread1=%d",isMain,[thread1 isMainThread]);
}
//第二种创建方式 类方法。 最多可以传一个参数
-(void) makeThread2beforeIOS10{
//类方法,不会返回NSThread对象,直接启动线程
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
}
//iOS 10又添加了两个方法创建线程。
// 需要iOS 10 才可以运行下面两个方法。否则会出错。
//第三种创建方式 实例方法
-(void) makeThread1FromIOS10{
NSThread *thread3 = [[NSThread a