1缕粹、控制線程生命周期<線程毖诺梗活>
2月培、解決NSTimer在滑動(dòng)時(shí)失效的問(wèn)題
當(dāng)scrollView滑動(dòng)的時(shí)候嘁字,定時(shí)器會(huì)發(fā)現(xiàn)失效
static int count = 0;
[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"count == %d",count++);
}];
原因:
NSTimer在RunLoop的Mode是NSDefaultRunLoopMode中的,
當(dāng)滑動(dòng)的時(shí)候RunLoop會(huì)切換到UITrackingRunLoopMode杉畜,所以NSTimer會(huì)失效纪蜒。
解決:
將Timer添加到NSRunLoopCommonModes模式下面
NSTimer *timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"count == %d",count++);
}];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
擴(kuò)展:
NSRunLoopCommonModes 不是一種真正的Mode,Mode有兩種
UITrackingRunLoopMode
NSDefaultRunLoopMode
NSRunLoopCommonModes可以認(rèn)為是一種標(biāo)記此叠,這個(gè)標(biāo)記包含UITrackingRunLoopMode和NSDefaultRunLoopMode
RunLoop和Timers的關(guān)系:
RunLoop中有一堆的Mode纯续,Mode中存在著Timers
3、監(jiān)控應(yīng)用卡頓
4灭袁、性能優(yōu)化