RunLoop(运行循环)-001-初探

RunLoop :运行循环(保证程序不退出!)(Event Loop)

目的:

1.保住当前线程的生命!!。

2.负责监听事件:iOS所有事件 触摸,时钟,网络等等!

3.要想保住一条线程的生命,让这条线程有执行不完的任务(死循环)!如果没有事件发送,会让程序进入休眠状态

001-时钟事件

 NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeMethod) userInfo:nil repeats:YES];

    //timer 添加到RunLoop运行循环中

    //NSDefaultRunLoopMode    默认模式!!

    //UITrackingRunLoopMode   UI模式!!

    //NSRunLoopCommonModes    占位模式!! UI&&默认! UI和默认都可以进行,互不影响

    //UI模式优先级最高!!  UI模式只会被触摸事件所触发!!

//    [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];

//    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

002-RunLoop启动和停止(退出)

@property(nonatomic,assign) BOOL finished;

    _finished = NO;

    HKThread * thread = [[HKThread alloc] initWithBlock:^{

        NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeMethod) userInfo:nil repeats:YES];

        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

        //[[NSRunLoop currentRunLoop] run];//就是一个死循环!! 无法停止UIApplicationMain也是死循环

        NSLog(@"come here");

        while (!self->_finished) {

            [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.0001]];

        }

    }];

    [thread start];//点击屏幕 线程被干掉

 

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    _finished = YES;

}

 

    HKThread * thread = [[HKThread alloc] initWithBlock:^{

        NSLog(@"%@-----",[NSThread currentThread]);

        while (true) {

            [[NSRunLoop currentRunLoop] run];

        }

    }];

    [thread start];

    

     [self performSelector:@selector(otherMethod) onThread:thread withObject:nil waitUntilDone:NO];

    -(void)otherMethod{

       NSLog(@"OtherMethod --- %@",[NSThread currentThread]);

    }

003-RunLoop source讲解

 Source : 事件源(输入源) 按照函数调用栈,Source分类

 Source0:非Source1 就是 例如用户点击事件

 Source1:系统内核事件或者其他线程间的通信

@property(nonatomic,strong)dispatch_source_t timer;//调度源 用于自动提交事件处理程序块、调度队列以响应外部事件

 //队列

    dispatch_queue_t queue = dispatch_get_global_queue(0,0);

    

    //创建一个定时器!!

    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

    

    //设置定时器

    dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1000000000, 0);//纳秒为单位 1000000000 为 1秒

    dispatch_source_set_event_handler(self.timer, ^{

        NSLog(@"-------%@",[NSThread currentThread]);

    });

    

    //启动定时器

     dispatch_resume(self.timer);

 

猜你喜欢

转载自www.cnblogs.com/StevenHuSir/p/RunLoop_Brief.html