前言:
我们会发现所有的source如果要起作用,就得加到runloop中去,如果一个runloop里面不包含任何资源的话,运行该runloop时会立马退出。APP的主线程的runloop我们没有往其中添加任何资源,为什么它还好好的运行。我们不添加,不代表框架没有添加,打印下main thread的runloop,会发现有很多资源。
NSRunloop只处理两种源,1.输入源 2.时间源。
输入源之下分为了:NSPort、自定义源 、performSelector:OnThread:delay:
举例:
1,时间源
timer需要运行是需要添加到runloop中去的
@interface ThreadCtr (){
NSTimer *_timer;
}
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadSelector:@selector(ThreadOne) toTarget:self withObject:nil];
}
- (void)ThreadOne{
NSLog(@"start thread");
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(stopTimer:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
NSLog(@"finish thread");
for (int i = 0; i < 5; i ++) {
NSLog(@"%d", i);
}
}
上面看到_timer在用scheduledTimerWithTimeInterval方式创建的,内部已经添加到runloop里面去了,不过子线程中runloop没有默认开启, 所以加了[[NSRunLoop currentRunLoop] run];这句开启runloop,这样在子线程中才能使time起作用,然后切记 [_timer invalidate];一定要在当前线程中调用,否则time一直在运行,子线程一直存在,出现了僵尸线程。
如果使用timerWithTimerInterval来初始化timer的就需要话就需要
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];