iOS-面试题 runloop(夯实基础学习笔记-温故知新3)
2020-06-20 本文已影响0人
朱允见
讲讲 RunLoop,项目中有用到吗?
runloop内部实现逻辑?
runloop和线程的关系?
timer 与 runloop 的关系?
程序中添加每3秒响应一次的NSTimer,当拖动tableview时timer可能无法响应要怎么解决?
runloop 是怎么响应用户操作的, 具体流程是什么样的?
说说runLoop的几种状态
runloop的mode作用是什么?
1. 什么是runloop?
-
运行循环
-
在程序运行过程中循环做一些事情
-
应用范畴
- 定时器(Timer)、PerformSelector
- GCD Async Main Queue
- 事件响应、手势识别、界面刷新
- 网络请求
- AutoreleasePool
2. RunLoop与线程
- 每条线程都有唯一的一个与之对应的RunLoop对象
- RunLoop保存在一个全局的Dictionary里,线程作为key,RunLoop作为value
- 线程刚创建时并没有RunLoop对象,RunLoop会在第一次获取它时创建
- RunLoop会在线程结束时销毁
- 主线程的RunLoop已经自动获取(创建),子线程默认没有开启RunLoop
3. RunLoop相关类
RunLoop相关类.pngimage.png
image.png
image.png
image.png
image.png
image.png
image.png
#import "YJThread.h"
@interface SubThread : NSThread
@end
@implementation SubThread
- (void)dealloc
{
NSLog(@"%s", __func__);
}
@end
@interface YJThread ()
@property(nonatomic,strong)SubThread *mythread;
@property(nonatomic,assign)BOOL isStop;
@property(nonatomic,copy)YJThreadBlock task;
@end
@implementation YJThread
- (instancetype)init
{
self = [super init];
if (self) {
__weak typeof(self)weakSelf = self;
self.mythread = [[SubThread alloc]initWithBlock:^{
[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
NSLog(@"00");
while (weakSelf&&!weakSelf.isStop) {
//获取线程
NSLog(@"11");
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
NSLog(@"22");
}
}];
[self.mythread start];
}
return self;
}
-(void)dotask:(YJThreadBlock)block {
self.task = block;
if(_isStop||block==nil)return;
[self performSelector:@selector(doit) onThread:self.mythread withObject:nil waitUntilDone:YES];
}
- (void)stop {
if(!self.mythread)return;
//注意 waitUntilDone:YES 等待线程执行完任务
[self performSelector:@selector(doStop) onThread:self.mythread withObject:nil waitUntilDone:YES];
}
-(void)doit{
if(self.task){
self.task();
}
}
-(void)doStop{
self.isStop = true;
CFRunLoopStop(CFRunLoopGetCurrent());
self.mythread = nil;
}
-(void)dealloc {
[self stop];
NSLog(@"%s 挂了",__func__);
}
@end