NSRunLoop

开发iOS这么久,总以为会RnuLoop了,但一旦说起便会哑口无言,这几天花费了大量时间去理解RunLoop,在此处做一个总结。

首先,我会从一段Python的代码中讲起,看不懂没关系,下面我会解释原理

import pygame
def main():
    pygame.init()
    # pygame.mixer.init()  # 混音器初始化
    #1. 创建窗口
    screen = pygame.display.set_mode((480,852),0,32)
    #2. 创建一个背景图片
    background = pygame.image.load("./feiji/background.png")
    while True:
        screen.blit(background, (0,0))
        pygame.display.update()
        time.sleep(0.02)

运行代码

950000D3-699E-40EE-8CE2-3F2B0F5BFB74.png

上面的代码中,我去掉while循环,便会出现这个窗口一闪即逝的情形,因为main是程序的主入口,它本身也是一个函数,函数运行完毕,内存释放,窗口自然消失,while的目的就是保持这个main函数的存活

一、下面我们回到我们的iOS中来,看我们iOS里面的main函数

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

将代码修改为

int main(int argc, char * argv[]) {
    @autoreleasepool {
//        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        int handle = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        NSLog(@"-----程序运行到这里------");
        return handle;
    }
}
运行之后发现,log -----程序运行到这里------是不会打印的

为什么会这样哪?
因为runloop就是我们上面python里面那个while循环,当然内部实现不仅仅一个while循环这么简单,苹果在内部封装了item,其次,while循环是销毁cpu资源的,runloop在内部做了处理,使cpu得到了最大的解放

1、下面讲述一下runLoop在代码使用中的理解(借用网上的例子修改的代码)

@property(nonatomic,strong) NSThread *myThread;
@property (nonatomic,assign)BOOL iden;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self alwaysLiveBackGoundThread];
    //[self alwaysLiveBackGoundThread1];
}
#pragma mark if
- (void)alwaysLiveBackGoundThread{
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(myThreadRun) object:@"etund"];
    self.myThread = thread;
    thread.name = @"test";
    [self.myThread start];
    
}
- (void)myThreadRun{
    NSLog(@"my thread run");
    NSLog(@"%@",[NSThread currentThread]);
    [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
     [[NSRunLoop currentRunLoop] run];
    NSLog(@"------------");
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"%@",self.myThread);
    [self performSelector:@selector(doBackGroundThreadWork) onThread:self.myThread withObject:nil waitUntilDone:NO];

}
- (void)doBackGroundThreadWork{
    NSLog(@"do some work %s",__FUNCTION__);
    NSLog(@"%@",[NSThread currentThread]);
    //    CFRunLoopStop(CFRunLoopGetCurrent());
}

启动应用并触摸屏幕后

2018-02-13 11:12:54.931493+0800 TestServer[1533:51118] my thread run
2018-02-13 11:12:54.931810+0800 TestServer[1533:51118] {number = 3, name = test}
2018-02-13 11:12:57.179297+0800 TestServer[1533:51022] {number = 3, name = test}
2018-02-13 11:12:57.179656+0800 TestServer[1533:51118] do some work -[ViewController doBackGroundThreadWork]
2018-02-13 11:12:57.179995+0800 TestServer[1533:51118] {number = 3, name = test}
2018-02-13 11:12:57.689079+0800 TestServer[1533:51022] {number = 3, name = test}
2018-02-13 11:12:57.689262+0800 TestServer[1533:51118] do some work -[ViewController doBackGroundThreadWork]
2018-02-13 11:12:57.689468+0800 TestServer[1533:51118] {number = 3, name = test}

不管触摸多少次屏幕,------------log始终不会打印,因为

[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];

就相当于一个while循环,可以想象成这段代码在该线程中加了一个while死循环,这个while循环在不停的执行(事实是苹果内部处理,在while循环没任务时,处于休眠状态),NSLog(@"------------");这段代码是永远无法被执行的
当我们执行

[self performSelector:@selector(doBackGroundThreadWork) onThread:self.myThread withObject:nil waitUntilDone:NO];

这段代码后,就好比往while循环里面添加了一个doBackGroundThreadWork任务,这个任务激活了正在休眠的while循环,while循环立即开始新的循环的工作,去处理这个任务,(while循环会有一个检查任务的规则,会先检查source,后面会讲到),这个任务处理完毕后,while再次进入休眠状态,这个任务,也就是doBackGroundThreadWork这个方法结束,该方法块内的内存释放;

OK,run方法介绍完毕
2、下面我们修改下myThreadRun这个方法里面的代码,其他地方的代码不改变

- (void)myThreadRun{
    NSLog(@"my thread run");
    NSLog(@"%@",[NSThread currentThread]);
    [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    NSLog(@"------------");
}

运行日志:

2018-02-13 11:24:35.191180+0800 TestServer[1619:58041] my thread run
2018-02-13 11:24:35.191446+0800 TestServer[1619:58041] {number = 3, name = test}
2018-02-13 11:24:38.947901+0800 TestServer[1619:57932] {number = 3, name = test}
2018-02-13 11:24:38.948119+0800 TestServer[1619:58041] do some work -[ViewController doBackGroundThreadWork]
2018-02-13 11:24:38.948284+0800 TestServer[1619:58041] {number = 3, name = test}
2018-02-13 11:24:38.948491+0800 TestServer[1619:58041] ------------
2018-02-13 11:24:44.296346+0800 TestServer[1619:57932] {number = 3, name = test}

我们看到在程序启动之后,线程卡在了

 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

这一行
触摸屏幕后打印了doBackGroundThreadWork方法里面log和NSLog(@"------------");,再次触摸屏幕这两个log均不打印
首先分析下面这段代码

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 

这段代码意思就是在未来时间开启while循环,这个时间永远无法到达,程序走到这行代码后,便会处于等待状态,也可以说是休眠状态,直到你指定的时间到达,while循环开启;
如果这个时间设置的特别短,while循环开启了,就是我们上面讲的第一种情况,NSLog(@"------------");是永远也不会再打印了
如果时间没到达,while循环未开启,我们执行了

[self performSelector:@selector(doBackGroundThreadWork) onThread:self.myThread withObject:nil waitUntilDone:NO];

就是在这个self.myThread线程中执行一个任务,这个任务便会激活while循环所在线程,导致这个线程不在处于休眠状态,继续执行,即使这个时间未到,线程也不会再继续等待,所以会把NSLog(@"------------");打印,之后线程执行完毕,线程销毁,内存释放,这个时候我们在执行performSelector方法,等于在一个nil的线程上执行,自然得不到响应
3、把runLoop放在while循环里面

- (void)myThreadRun{
    NSLog(@"my thread run");
    NSLog(@"%@",[NSThread currentThread]);
    self.iden = YES;
    while (self.iden) {
        NSLog(@"---while1----");
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        NSLog(@"---while2----");
    }
    NSLog(@"------------");
}

我们触摸屏幕执行下面的代码

- (void)doBackGroundThreadWork{
    NSLog(@"do some work %s",__FUNCTION__);
    NSLog(@"%@",[NSThread currentThread]);
}

会看到触摸一次---while2----打印一次,这是因为每触摸一次,等于取消了runloop的等待时间,也就是等于取消了runloop,程序继续执行while (self.iden)循环,在此循环到runloop又重新开启等待
我们修改doBackGroundThreadWork1代码

- (void)doBackGroundThreadWork{
    NSLog(@"do some work %s",__FUNCTION__);
    NSLog(@"%@",[NSThread currentThread]);
    self.iden = NO;
}

就会发现while (self.iden) 执行一次,便退出,最后打印了------------之后,整个线程销毁

之后在说些基础点,runloop有mode和item,mode系统只给我们提供了2种NSDefaultRunLoopMode和NSRunLoopCommonModes,item指定了3中类型,source,timers,observer
在我们平时开发中遇到的一个问题,定时器和滚动屏幕同时操作,定时器触发时间延时问题,如果为了便于理解可以这样考虑,在runloop的while循环里面添加了if判断
while(条件){
if(mode == default){
......
}
else .....
}
(这纯属我个人的便于理解做的假象,有见解大家留言,勿喷)
if(mode == default) 就是处理定时器的事件
如果滚动屏幕,就是if(mode==EventTracking)处理了滚屏事件,所以导致定时器未做处理

其次,每一个mode都得指定item,即item不能为nil,最开始1中的例子,如果runloop不指定port,

[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];

这行代码如果去掉,就相当于runloop未开启

二、runloop每次循环的处理

先看这张图


2312304-8e64b79a92d53567.png

上面也说了,需要为mode指定item,item包含3个类型,source,timers,observer,这三种类型处理的顺序就是图中所标注的流程,其实这也就是苹果内部的处理方式,想深入了解的可以在仔细研究。
最后一点,runloop内部的while循环是怎么实现暂停的,我个人想法是信号量

 dispatch_semaphore_t sema = dispatch_semaphore_create(1);
while(true){
     dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    ......
}

一旦有任务进来,便执行dispatch_semaphore_signal(sema);
让信号量加1
这样就解决了线程阻塞,并且不消耗cpu的办法
demo地址:下载
(以上是个人理解的推断,有高见欢迎评论)

你可能感兴趣的:(NSRunLoop)