NSRunLoop其實本質就是死循環;
作用:Runloop--運行循環
- 1.保證程序不退出
- 2.負責監聽事件、觸摸、時鐘、網絡事件
- 如果沒有事件發生,就處于休眠狀態
引申一個問題:循環和遞歸的區別
- 遞歸就是自己調用自己,每調用一次方法壓棧一次,相當于在內存開辟了一個空間,每次調用都開辟一個空間,會造成內存空間溢出,遞歸就結束了,循環沒事。
- 2.遞歸是不確定循環次數的時候用,而for循環是知道循環次數;
具體使用
1.
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];//雖然蘋果幫我們自動加入了運行循環,但是模式是普通模式。就造成處理UI模式式,不能執行普通模式(比如就會造成操作UI,timer停止的問題)
2.手動加入runloop
NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
[[NSRunLoop currentRunLoop] run];
/*
NSRunLoopMode 模式:
1. 普通模式:NSDefaultRunLoopMode
2.UITrackingRunLoopMode//UI模式比如拖拽的時候,才會調用timer,松手就不會調用timer事件
3.占位模式NSRunLoopCommonModes //這個模式可以解決處理UI模型,同時處理普通模式
*/
3. GCD定時器(要注意的是,把dispatch_source_t timer變為全局變量)不然不會執行Block回調
dispatch_queue_t queue = dispatch_get_main_queue();//dispatch_get_global_queue(0, 0)全局隊列
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW,0.001 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
static NSInteger i =1;
self.disPlayLabel.text= [ @(6 +i) stringValue];
i++;
NSThread * thread =[NSThread currentThread];
NSLog(@"當前線程===%@",thread);
});
dispatch_resume(_timer);
Runloop與線程
//想要保住線程,讓線程有執行不完的任務!線程就不會釋放了,而不是強引用
//子線程
NSThread * thread = [[NSThread alloc] initWithBlock:^{
NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
//Runloop---一條線程上面的runloop默認是不循環,所以執行run函數,才能死循環
[[NSRunLoop currentRunLoop] run];//死循環
NSLog(@"來了");
}];
[thread start];
-(void) timerMethod{
NSLog(@"come here");
NSLog(@"timer 來了:%@",[NSThread currentThread]);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"主線程===%@",[NSThread currentThread]);
[NSThread exit];//干掉主線程,但程序不會崩,其它線程一樣可以照常運行,在iOS里面就會出現主線程被干掉,界面卡死
}