NSRunLoop其實(shí)本質(zhì)就是死循環(huán)臂外;
作用:Runloop--運(yùn)行循環(huán)
- 1.保證程序不退出
- 2.負(fù)責(zé)監(jiān)聽事件庐冯、觸摸盈滴、時(shí)鐘欲账、網(wǎng)絡(luò)事件
- 如果沒(méi)有事件發(fā)生五鲫,就處于休眠狀態(tài)
引申一個(gè)問(wèn)題:循環(huán)和遞歸的區(qū)別
- 遞歸就是自己調(diào)用自己,每調(diào)用一次方法壓棧一次,相當(dāng)于在內(nèi)存開辟了一個(gè)空間,每次調(diào)用都開辟一個(gè)空間,會(huì)造成內(nèi)存空間溢出溺职,遞歸就結(jié)束了,循環(huán)沒(méi)事。
- 2.遞歸是不確定循環(huán)次數(shù)的時(shí)候用,而for循環(huán)是知道循環(huán)次數(shù)浪耘;
具體使用
1.
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];//雖然蘋果幫我們自動(dòng)加入了運(yùn)行循環(huán)乱灵,但是模式是普通模式。就造成處理UI模式式七冲,不能執(zhí)行普通模式(比如就會(huì)造成操作UI痛倚,timer停止的問(wèn)題)
2.手動(dòng)加入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模式比如拖拽的時(shí)候,才會(huì)調(diào)用timer癞埠,松手就不會(huì)調(diào)用timer事件
3.占位模式NSRunLoopCommonModes //這個(gè)模式可以解決處理UI模型状原,同時(shí)處理普通模式
*/
3. GCD定時(shí)器(要注意的是,把dispatch_source_t timer變?yōu)槿肿兞浚┎蝗徊粫?huì)執(zhí)行Block回調(diào)
dispatch_queue_t queue = dispatch_get_main_queue();//dispatch_get_global_queue(0, 0)全局隊(duì)列
_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(@"當(dāng)前線程===%@",thread);
});
dispatch_resume(_timer);
Runloop與線程
//想要保住線程苗踪,讓線程有執(zhí)行不完的任務(wù)颠区!線程就不會(huì)釋放了,而不是強(qiáng)引用
//子線程
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默認(rèn)是不循環(huán),所以執(zhí)行run函數(shù)通铲,才能死循環(huán)
[[NSRunLoop currentRunLoop] run];//死循環(huán)
NSLog(@"來(lái)了");
}];
[thread start];
-(void) timerMethod{
NSLog(@"come here");
NSLog(@"timer 來(lái)了:%@",[NSThread currentThread]);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"主線程===%@",[NSThread currentThread]);
[NSThread exit];//干掉主線程毕莱,但程序不會(huì)崩,其它線程一樣可以照常運(yùn)行颅夺,在iOS里面就會(huì)出現(xiàn)主線程被干掉朋截,界面卡死
}