runLoop运行模式示例代码

来源:互联网 发布:ios数据恢复工具 编辑:程序博客网 时间:2024/04/30 04:06

runLoop运行模式示例代码

通过 timer2 这种方式创建定时器,不再需要手动添加到runloop里面,该方法内部会自动添加,并且设置运行模式为默认模式。

要注意的是 子线程的runloop是需要自己创建的

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{//    [self timer2];    [NSThread detachNewThreadSelector:@selector(timer2) toTarget:self withObject:nil];}-(void)timer{    //创建定时器   NSTimer *timer= [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];        //添加定时器到RunLoop中    //参数1:定时器   参数2: runloop的运行模式    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];}-(void)timer2{    NSRunLoop *runloop=[NSRunLoop currentRunLoop];    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];    [runloop run];}-(void)run{    NSLog(@"------%@-------%@",[NSThread currentThread],[NSRunLoop currentRunLoop].currentMode);}@end




0 0