RunLoop其实没有我们想的那么难

作者: flowerflower | 来源:发表于2018-01-31 13:48 被阅读85次
12.jpg

目录
一、纯纯的RunLoop(上小菜)
二、RunLoop与多线程相结合使用(上大菜)

一、纯纯的RunLoop(上小菜)

在研究RunLoop之前,我们首先需要了接一下程序入口,也就是main.m函数

首页我们来看此段代码

int main(int argc, char * argv[]) {
    @autoreleasepool {
        NSLog(@"来了");

   int a = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        NSLog(@"你猜我会不会被打印");
        return a;
    }
}

你猜结果会打印什么???

打印一个,还是两个都会打印?或者只打印其中一个??

揭晓答案

图片.png

我们再来看里面的几个参数

int main(int argc, char * argv[]) {
    @autoreleasepool {
        NSLog(@"来了");
/*
第一,二个参数不用管,这直接是传过来的。
第三个参数:UIApplication
第四个参数:类名转字符串好处: NSStringFromClass 防止输入错误  
AppDelegate:必须要遵守UIApplicationDelegate协议
**/
//为啥第二个log不会被打印呢???
/**
说明这里面开启一个RunLoop死循环,导致代码不往下执行
UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]))
开启死循环的目的何在?
  • 保证程序不退出
  • 负责监听用户的行为(触摸、时钟、网络事件)
  • 如果没有事件发生,会做一个特殊处理,让程序进入休眠(休眠不表示不耗性能,而是说耗性非常低而已)状态。

Demo演练

是否会被打印案例一:

- (void)viewDidLoad {
    [super viewDidLoad];
  NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
}
- (void)run{   
    NSLog(@"来了--%@",[NSThread currentThread]);
}

是否会被打印案例二:

    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];

答案揭晓
案例一不会打打印,案例二会打印

分析:
案例一不会被打印的原因:

timer事件要想被监听 需要将事件加到runloop里面
改造成

    NSRunLoop *runLoop  = [NSRunLoop currentRunLoop];
  [runLoop addTimer:timer forMode:NSRunLoopCommonModes];

案例二会被打印的原因:因为这方法里面封装了以上的步骤

我们再来看一个例子:


2121.gif

为什么拖拽时就停止打印了

也许到这里你就有疑问了,改下模式不就好了么,但是我们这里要说的是原理,知其根源才是重点。


图片.png

解决方式:

- (void)viewDidLoad {
    [super viewDidLoad];
    
      NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
 
     NSRunLoop *runLoop  = [NSRunLoop currentRunLoop];
     /**
      NSDefaultRunLoopMode:默认模式
      UITrackingRunLoopMode:UI模式
      NSRunLoopCommonModes:占位模式(上面两种模式的结合体)
      如果使用UITrackingRunLoopMode,就是说明Timer加在了UI模式下,
   拖拽时就会打印了,但是停止拖拽时,则不会打印
  如果使用NSRunLoopCommonModes模式,则不管是拖拽还是停止拖拽都会打印。。
      */
      [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
     
    self.view.backgroundColor = [UIColor redColor];
}
- (void)run{
    
    NSLog(@"来了--%@",[NSThread currentThread]);
}

接下来来研究一些有意思的东西。。。

二、RunLoop与多线程相结合使用(上大菜)

最终需求:

  • 1.打印run起来了 + 打印来了--[NSThread currentThread]+打印来了来了来了
  • 2.不卡顿
- (void)viewDidLoad {
    [super viewDidLoad];
    
      NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
 
     NSRunLoop *runLoop  = [NSRunLoop currentRunLoop];
  
      [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
    
    self.view.backgroundColor = [UIColor redColor];
}
- (void)run{
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"来了--%@",[NSThread currentThread]);
}
21.gif

意外发生了

让他睡了一秒,导致卡顿的事情发生了。。

解决卡顿意外事件,但是需求1问题依然存在
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    NSThread *thread = [[Thread alloc]initWithBlock:^{
      
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
        
        NSRunLoop *runLoop  = [NSRunLoop currentRunLoop];
        [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
        //RunLoop: 一条线程上面的RunLoop模式是不循环的
        //一旦run起来之后就干不掉了
          [[NSRunLoop currentRunLoop]run]; //死循环
        NSLog(@"来了来了来了");

    [thread start];
}
- (void)run{
    NSLog(@"run起来了");
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"来了--%@",[NSThread currentThread]);
}

分析发现:

只要我们让他run起来了,就干不掉了,那么他就会一直执行run方法。来了来了来了是不会被打印的,那么怎么干掉run呢,让他能打印来了来了来了呢。

那么如何干掉run,成为本章的核心话题,请看下面

@interface ViewController ()

//保住OC对象的生命 但是线程是CPU调度的 线程不是OC对象就可以保住的
//一条线程的生命,只能通过线程的任务保住。。让线程有执行不完的任务,线程就不会释放了
@property(nonatomic,strong) Thread *thread;  //
// 使用一个BOOL进行标记
@property(nonatomic,assign) BOOL  isFlag;  //

@end

@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    _isFlag = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _isFlag = NO;
    self.view.backgroundColor = [UIColor redColor];
    NSThread *thread = [[Thread alloc]initWithBlock:^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
        NSRunLoop *runLoop  = [NSRunLoop currentRunLoop];
        
        [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
        while (!_isFlag) {
            [[NSRunLoop currentRunLoop]runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.00001]];
        }
        NSLog(@"来了来了来了");
//
//        while (true) {
//              //从时间队列中取出时间来处理
//            //让线程有执行不完的任务,线程就不会释放了  保证线程不挂
//        }
    }];
    [thread start];
}
- (void)run{
    NSLog(@"run起来了");
    [NSThread sleepForTimeInterval:1.0];
    NSLog(@"来了--%@",[NSThread currentThread]);
}
1212.gif

相关文章

  • RunLoop其实没有我们想的那么难

    目录一、纯纯的RunLoop(上小菜)二、RunLoop与多线程相结合使用(上大菜) 一、纯纯的RunLoop(上...

  • 爱情其实没有我们想的那么难

    从前段时间的前任3到现在后来的我们, 或许因为结局的现实,引起大家共鸣。 每个人可能都会有一个爱而不得人, 所以电...

  • 摆脱恐惧,其实没有我们想的那么难

    什么样的人是优秀的人呢?考上好的大学,拥有很多钱的人,虽然他们很优秀,但是这个并不是唯一的标准。 就像俞敏洪在《摆...

  • 其实写书没有想的那么难!

    可能很多人觉得,写作是件遥远的事,和自己没有多大关系。有些人甚至妄自菲薄,觉得自己肯定没有写作的能力,进而丧失了一...

  • 赚钱其实没有你们想的那么难

    最近几年看了太多太多什么教赚钱教项目的,这个搬运,那个上传等等,给人看的感觉是好像一夜就能暴富的感觉,只能说现在的...

  • 坚持没有我们想的那么难

    一旦开始读书了,就坚持下来。 如果觉得时间不够用,就利用零碎时间,利用喝一杯茶的时间,利用上厕所的...

  • 其实没有那么难

    其实

  • 其实没有那么难

    心里一放点事儿就睡不着觉,翻来覆去的,真没能耐…… 都是些什么撒旦魔鬼邪灵呢?我坐在沙发上思考起来:...

  • 其实,起诉打官司没有想的那么难

    年底了,民庭的立案大厅还是很忙,应该说是越来越忙,不过这周好一点。因为是镇上的派出法庭,来的人很多都是附近村镇的人...

  • 幸福,其实没有那么难

    你知道幸福的味道是什么样的吗? 幸福的味道是早晨刚下过小雨的街道,闻起来的一刹那像极了大学校园某一个早起晨读的早上...

网友评论

    本文标题:RunLoop其实没有我们想的那么难

    本文链接:https://www.haomeiwen.com/subject/jwhkzxtx.html