GitHub 中文社区iOS 开发每天分享优质文章iOS开发技术

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

2018-01-31  本文已影响85人  flowerflower
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与多线程相结合使用(上大菜)

最终需求:

- (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
上一篇 下一篇

猜你喜欢

热点阅读