主线程不死是因为主线程里面有一个RunLoop,RunLoop里面有一个do while死循环,保证了程序的不退出
那么如果我们有一个需求,需要一直在后台进行某个耗时操作,比如检查联网状态,比如扫描用户的某些行为等等.
这时候肯定要在子线程进行,如果能保证一个子线程的不死,就能避免频繁的创建与销毁线程.
方法:
模仿主线程不死的操作
1.创建并强引用线程
2.往该线程里添加RunLoop
3.往RunLoop里面添加事务(source,timer,observer),保证RunLoop不退出
4.RunLoop run
这样我们就可以随时调用该线程处理一些任务了,代码如下
#import "ViewController.h"
#import "GQThread.h"
@interface ViewController ()
@property (nonatomic,strong)GQThread * thread; // 重写了dealloc方法,查看线程是够销毁
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.thread = [[GQThreadalloc] initWithTarget:selfselector:@selector(threadBegin1)object:nil];
self.thread.name =@"不死线程";
[self.threadstart];
}
// threadBegin123都可以让线程不死
- (void)threadBegin1 {
@autoreleasepool{ //必须的,下面两个方法也应该加上,处理一些autorelease对象
[[NSRunLoop currentRunLoop] addPort:[NSPortport] forMode:NSDefaultRunLoopMode];
[[NSRunLoopcurrentRunLoop] run];
NSLog(@"threadBegin");//主句代码不会执行了,因为[[NSRunLoopcurrentRunLoop] run]一直在跑圈,在RunLoop内部会不断去查看该线程有没有任务要处理,若有,就让它处理一下
}
}
- (void)threadBegin2{
while (1) {
[[NSRunLoopcurrentRunLoop] run];
}
}
- (void)threadBegin3{
[NSTimerscheduledTimerWithTimeInterval:2.0target:selfselector:@selector(test)userInfo:nilrepeats:YES];
[[NSRunLoopcurrentRunLoop] run];
}
// 自定义的一些任务给该线程执行
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[selfperformSelector:@selector(test)onThread:self.threadwithObject:nilwaitUntilDone:NO];
}
- (void)test
{
NSLog(@"***********test2*******%@", [NSThreadcurrentThread]);
// NSLog(@"%@", [NSRunLoop currentRunLoop]);
}