iOS-面试题 runloop(夯实基础学习笔记-温故知新3)

2020-06-20  本文已影响0人  朱允见

讲讲 RunLoop,项目中有用到吗?
runloop内部实现逻辑?
runloop和线程的关系?
timer 与 runloop 的关系?
程序中添加每3秒响应一次的NSTimer,当拖动tableview时timer可能无法响应要怎么解决?
runloop 是怎么响应用户操作的, 具体流程是什么样的?
说说runLoop的几种状态
runloop的mode作用是什么?

1. 什么是runloop?
2. RunLoop与线程
3. RunLoop相关类
RunLoop相关类.png
image.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

上一篇下一篇

猜你喜欢

热点阅读