NSRunLoop--线程

NSRunLoop其实本质就是死循环;
作用:Runloop--运行循环

  • 1.保证程序不退出
  • 2.负责监听事件、触摸、时钟、网络事件
    1. 如果没有事件发生,就处于休眠状态

引申一个问题:循环和递归的区别

    1. 递归就是自己调用自己,每调用一次方法压栈一次,相当于在内存开辟了一个空间,每次调用都开辟一个空间,会造成内存空间溢出,递归就结束了,循环没事。
  • 2.递归是不确定循环次数的时候用,而for循环是知道循环次数;

具体使用

1.
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];//虽然苹果帮我们自动加入了运行循环,但是模式是普通模式。就造成处理UI模式式,不能执行普通模式(比如就会造成操作UI,timer停止的问题)

2.手动加入runloop
NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [[NSRunLoop currentRunLoop] run];
/*
NSRunLoopMode 模式: 
1. 普通模式:NSDefaultRunLoopMode 
2.UITrackingRunLoopMode//UI模式比如拖拽的时候,才会调用timer,松手就不会调用timer事件  
3.占位模式NSRunLoopCommonModes //这个模式可以解决处理UI模型,同时处理普通模式
*/

3. GCD定时器(要注意的是,把dispatch_source_t timer变为全局变量)不然不会执行Block回调
dispatch_queue_t queue = dispatch_get_main_queue();//dispatch_get_global_queue(0, 0)全局队列
     _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW,0.001 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        static NSInteger i =1;
        self.disPlayLabel.text= [ @(6 +i) stringValue];
        i++;
        NSThread * thread =[NSThread currentThread];
        NSLog(@"当前线程===%@",thread);
    });
    dispatch_resume(_timer);

Runloop与线程

//想要保住线程,让线程有执行不完的任务!线程就不会释放了,而不是强引用
 //子线程
    NSThread * thread = [[NSThread alloc] initWithBlock:^{
        NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        
        //Runloop---一条线程上面的runloop默认是不循环,所以执行run函数,才能死循环
        [[NSRunLoop currentRunLoop] run];//死循环
        
        NSLog(@"来了");
    }];
    [thread start];

-(void) timerMethod{
    NSLog(@"come here");
    NSLog(@"timer 来了:%@",[NSThread currentThread]);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"主线程===%@",[NSThread currentThread]);
    [NSThread exit];//干掉主线程,但程序不会崩,其它线程一样可以照常运行,在iOS里面就会出现主线程被干掉,界面卡死
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1,NSObject中description属性的意义,它可以重写吗?答案:每当 NSLog(@"")函数中出现 ...
    eightzg阅读 9,629评论 2 19
  • 本文将从以下几个部分来介绍多线程。 第一部分介绍多线程的基本原理。 第二部分介绍Run loop。 第三部分介绍多...
    曲年阅读 5,020评论 2 14
  • 这是AF2.x经典的代码: 首先我们要明确一个概念,线程一般都是一次执行完任务,就销毁了。 而添加了runloop...
    有梦想的老伯伯阅读 6,062评论 5 13
  • 一、什么是runloop 字面意思是“消息循环、运行循环”。它不是线程,但它和线程息息相关。一般来讲,一个线程一次...
    WeiHing阅读 12,526评论 11 111
  • 我不信 这中秋的豪热 能将人的尊严蒸发 但我明明看到 某前领导 用大噪门证明着 活着只为 某笔奖金 还有 偏激
    第一闲人阅读 994评论 0 1