RunLoop(运行循环)

什么是RunLoop

从字面意思看

运行循环
跑圈

基本作用

保持程序的持续运行
处理App中的各种事件(比如触摸事件、定时器事件、Selector事件)
节省CPU资源,提高程序性能:该做事时做事,该休息时休息
......

如果没有RunLoop

int main(int argc, char * argv[]) {
    NSLog(@"execute main function"); // 程序开始
    return 0; // 程序结束
}

没有RunLoop的情况下
第3行后程序就结束了

如果有了RunLoop

int main(int argc, char * argv[]) {
    BOOL running = YES; // 程序开始
    do {
        // 执行各种任务,处理各种事件
             // ......
    } while (running);
    return 0;
}

有RunLoop的情况下
由于main函数里面启动了个RunLoop,所以程序并不会马上退出,保持持续运行状态

main函数中的RunLoop

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

第3行代码的UIApplicationMain函数内部就启动了一个RunLoop
所以UIApplicationMain函数一直没有返回,保持了程序的持续运行
这个默认启动的RunLoop是跟主线程相关联的

RunLoop资料

苹果官方文档

苹果官方文档

CFRunLoopRef是开源的

CFRunLoopRef是开源的

RunLoop与线程

  • 每条线程都有唯一的一个与之对应的RunLoop对象

  • 主线程的RunLoop已经自动创建好了,子线程的RunLoop需要主动创建

  • RunLoop在第一次获取时创建,在线程结束时销毁

获得RunLoop对象

在子线程中苹果不会主动创建RunLoop,必须我们手动创建,其创建为懒加载,所以只需要在子线程中调用[NSRunLoop currentRunLoop]

Foundation

[NSRunLoop currentRunLoop]; // 获得当前线程的RunLoop对象
[NSRunLoop mainRunLoop]; // 获得主线程的RunLoop对象

Core Foundation

CFRunLoopGetCurrent(); // 获得当前线程的RunLoop对象
CFRunLoopGetMain(); // 获得主线程的RunLoop对象

RunLoop相关类

Core Foundation中关于RunLoop的5个类
CFRunLoopRef
CFRunLoopModeRef
CFRunLoopSourceRef
CFRunLoopTimerRef
CFRunLoopObserverRef

RunLoop相关类

CFRunLoopModeRef

CFRunLoopModeRef代表RunLoop的运行模式

一个 RunLoop 包含若干个 Mode,每个Mode又包含若干个Source/Timer/Observer

每次RunLoop启动时,只能指定其中一个 Mode,这个Mode被称作 CurrentMode

如果需要切换Mode,只能退出Loop,再重新指定一个Mode进入

这样做主要是为了分隔开不同组的Source/Timer/Observer,让其互不影响

系统默认注册了5个Mode:

kCFRunLoopDefaultMode:App的默认Mode,通常主线程是在这个Mode下运行

UITrackingRunLoopMode:界面跟踪 Mode,用于 ScrollView 追踪触摸滑动,保证界面滑动时不受其他 Mode 影响

UIInitializationRunLoopMode: 在刚启动 App 时第进入的第一个 Mode,启动完成后就不再使用

GSEventReceiveRunLoopMode: 接受系统事件的内部 Mode,通常用不到

kCFRunLoopCommonModes: 这是一个占位用的Mode,不是一种真正的Mode

CFRunLoopSourceRef

CFRunLoopSourceRef是事件源(输入源)

  • 以前的分法

    • Port-Based Sources
    • Custom Input Sources
    • Cocoa Perform Selector Sources
  • 现在的分法

    • Source0:非基于Port的
    • Source1:基于Port的

CFRunLoopTimerRef

CFRunLoopTimerRef是基于时间的触发器

基本上说的就是NSTimer

CFRunLoopObserverRef

CFRunLoopObserverRef是观察者,能够监听RunLoop的状态改变

可以监听的时间点有以下几个

typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
    kCFRunLoopEntry = (1UL << 0), // 即将进入Loop
    kCFRunLoopBeforeTimers = (1UL << 1), // 几件该处理Timer
    kCFRunLoopBeforeSources = (1UL << 2), // 即将处理Sources
    kCFRunLoopBeforeWaiting = (1UL << 5), // 即将进入休眠
    kCFRunLoopAfterWaiting = (1UL << 6), // 刚从休眠中换唤醒
    kCFRunLoopExit = (1UL << 7), // 即将退出Loop
    kCFRunLoopAllActivities = 0x0FFFFFFFU
};

RunLoop处理逻辑-官方版

RunLoop处理逻辑-官方版

RunLoop处理逻辑

RunLoop处理逻辑-整理

RunLoop应用

  • NSTimer
  • ImageView显示
  • PerformSelector
  • 常驻线程
  • 自动释放池

运行时模式问题

即使已经进入到别的页面,这个定时器依然可用

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // RunLoop 定时器默认在NSDefaultRunLoopMode模式,但是可以修改模式
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];

   //  NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
   // [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

- (void)run {
    NSLog(@"【Run】");
}
@end

等价于下面程序

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 等价于
    NSTimer * timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
    //现在RunLoop只有在默认的模式下可用,一旦运行进入其他模式,这时候定时器就不会工作
    // 当我们滑动屏幕,RunLoop就会进入UITrackingRunLoopMode模式
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)run {
    NSLog(@"【Run】");
}
@end

如果我们想要在默认模式,以及滑动模式都可以执行操作,我们就需要设置如下

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
    //现在RunLoop只有在默认的模式下可用,一旦运行进入其他模式,这时候定时器就不会工作
    // 当我们滑动屏幕,RunLoop就会进入UITrackingRunLoopMode模式
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

    // 多种模式下
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
}

- (void)run {
    NSLog(@"【Run】");
}
@end

也等同雨如下

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 等价于
    NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
    //现在RunLoop只有在默认的模式下可用,一旦运行进入其他模式,这时候定时器就不会工作
    // 当我们滑动屏幕,RunLoop就会进入UITrackingRunLoopMode模式
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)run {
    NSLog(@"【Run】");
}
@end


标记为 NSRunLoopCommonModes的模式:UITrackingRunLoopMode以及NSDefaultRunLoopMode

RunLoop实现

需求:程序中有一个UIImageView和一个UITextView,当点击屏幕的时候开始下载显示图片,但下载的同时可能会滚动TextView,这时候如果显示图片的时候可能就会有点卡(因为图片如果很大,渲染时候就会很耗时间)

#import "ViewController.h"

@interface ViewController ()
/** 背景图片 */
@property (nonatomic,weak) UIImageView * imageView;
/** textView */
@property (nonatomic,weak) UITextView * textView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self textView];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://upload.hljtv.com/2014/1105/1415160173910.jpg"]];
    UIImage * image = [UIImage imageWithData:data];
    [self.imageView performSelector:@selector(setImage:) withObject:image afterDelay:3.0];
}

#pragma mark - 懒加载
- (UIImageView *)imageView{
    if (_imageView == nil) {
        UIImageView * imageView = [[UIImageView alloc] init];
        imageView.bounds = CGRectMake(0, 0, 200, 200);
        imageView.center = self.view.center;
        _imageView = imageView;
        [self.view addSubview:imageView];
    }
    return _imageView;
}

- (UITextView *)textView{
    if (_textView == nil) {
        UITextView * textView = [[UITextView alloc] init];
        textView.bounds = CGRectMake(0, 0, 200, 100);
        textView.center = CGPointMake(100, 100);
        textView.text = @"阑干独倚天涯客。心影暗凋风叶寂。千山秋入雨中青,一雁暮随云去急。霜花强弄春颜色。相吊年光浇大白。海烟沈处倒残霞,一杼鲛绡和泪织。▼水绕陂田竹绕篱,榆钱落尽槿花稀。夕阳牛背无人卧,带得寒鸦两两归。▼次吴江,小泊,夜饮僧窗惜别。邦人赵簿携小妓侑尊。连歌数阕,皆清真词。酒尽已四鼓。赋此词饯尹梅津。送客吴皋,正试霜夜冷,枫落长桥。望天不尽,背城渐杳,离亭黯黯,恨永迢迢。翠香零落红衣老,暮愁锁、残柳眉梢。念瘦腰、沈郎旧日,曾系兰桡。仙人凤咽琼箫,怅断魂送远,《九▼阑干独倚天涯客。心影暗凋风叶寂。千山秋入雨中青,一雁暮随云去急。霜花强弄春颜色。相吊年光浇大白。海烟沈处倒残霞,一杼鲛绡和泪织。▼水绕陂田竹绕篱,榆钱落尽槿花稀。夕阳牛背无人卧,带得寒鸦两两归。▼次吴江,小泊,夜饮僧窗惜别。邦人赵簿携小妓侑尊。连歌数阕,皆清真词。酒尽已四鼓。赋此词饯尹梅津。送客吴皋,正试霜夜冷,枫落长桥。望天不尽,背城渐杳,离亭黯黯,恨永迢迢。翠香零落红衣老,暮愁锁、残柳眉梢。念瘦腰、沈郎旧日,曾系兰桡。仙人凤咽琼箫,怅断魂送远,《九▼";
        [self.view addSubview:textView];
        _textView = textView;

    }
    return _textView;
}
@end


操作说明:这时候如果我们滑动TextView,那么下载显示图片就会同时进行,但是可能会很卡

解决办法:推迟UIImageView的显示,即使是图片已经下载完成后也不会显示

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://upload.hljtv.com/2014/1105/1415160173910.jpg"]];
    UIImage * image = [UIImage imageWithData:data];
    [self.imageView performSelector:@selector(setImage:) withObject:image afterDelay:3.0 inModes:@[NSDefaultRunLoopMode]];
}

解释:这样就会让图片延迟显示。当在滚动的时候是在track模式,但是我们在default模式下添加显示图片。这样当模式从track模式重新回到default模式下,就会执行显示图片

常驻线程

一个常驻线程来监控一些信息之类的东西


#import "ViewController.h"

@interface ViewController ()
/** 背景图片 */
@property (nonatomic,weak) UIImageView * imageView;
/** textView */
@property (nonatomic,weak) UITextView * textView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self textView];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [thread start];
}

- (void)run {
    NSLog(@"---run---");
}



#pragma mark - 懒加载
- (UIImageView *)imageView{
    if (_imageView == nil) {
        UIImageView * imageView = [[UIImageView alloc] init];
        imageView.bounds = CGRectMake(0, 0, 200, 200);
        imageView.center = self.view.center;
        _imageView = imageView;
        [self.view addSubview:imageView];
    }
    return _imageView;
}

- (UITextView *)textView{
    if (_textView == nil) {
        UITextView * textView = [[UITextView alloc] init];
        textView.bounds = CGRectMake(0, 0, 200, 100);
        textView.center = CGPointMake(100, 100);
        textView.text = @"阑干独倚天涯客。心影暗凋风叶寂。千山秋入雨中青,一雁暮随云去急。霜花强弄春颜色。相吊年光浇大白。海烟沈处倒残霞,一杼鲛绡和泪织。▼水绕陂田竹绕篱,榆钱落尽槿花稀。夕阳牛背无人卧,带得寒鸦两两归。▼次吴江,小泊,夜饮僧窗惜别。邦人赵簿携小妓侑尊。连歌数阕,皆清真词。酒尽已四鼓。赋此词饯尹梅津。送客吴皋,正试霜夜冷,枫落长桥。望天不尽,背城渐杳,离亭黯黯,恨永迢迢。翠香零落红衣老,暮愁锁、残柳眉梢。念瘦腰、沈郎旧日,曾系兰桡。仙人凤咽琼箫,怅断魂送远,《九▼阑干独倚天涯客。心影暗凋风叶寂。千山秋入雨中青,一雁暮随云去急。霜花强弄春颜色。相吊年光浇大白。海烟沈处倒残霞,一杼鲛绡和泪织。▼水绕陂田竹绕篱,榆钱落尽槿花稀。夕阳牛背无人卧,带得寒鸦两两归。▼次吴江,小泊,夜饮僧窗惜别。邦人赵簿携小妓侑尊。连歌数阕,皆清真词。酒尽已四鼓。赋此词饯尹梅津。送客吴皋,正试霜夜冷,枫落长桥。望天不尽,背城渐杳,离亭黯黯,恨永迢迢。翠香零落红衣老,暮愁锁、残柳眉梢。念瘦腰、沈郎旧日,曾系兰桡。仙人凤咽琼箫,怅断魂送远,《九▼";
        [self.view addSubview:textView];
        _textView = textView;

    }
    return _textView;
}

@end


说明:当点击的时候执行run方法,但是之后线程就死掉了。
监听线程死掉的方法可以继承NSTread,然后重写他的dealloc方法。

改进1

因为每次执行完之后线程都会死亡,这时候会有一个想法就是添加一个全局的引用

#import "ViewController.h"

@interface ViewController ()
/** 背景图片 */
@property (nonatomic,weak) UIImageView * imageView;
/** textView */
@property (nonatomic,weak) UITextView * textView;
/** 线程的强引用 */
@property (nonatomic,strong) NSThread * thread;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self textView];
    self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.thread start];
}

- (void)run {
    NSLog(@"---run---");
}


解释:这样子看上去好像是可行的,添加了全局的引用,这样子线程就不会死亡,但是当我们点击第一次的时候是正常的,但是当我们再次点击的时候程序就会crash

原因:每次线程执行完之后就会是一种消亡状态,是不可以重新start的
#import "ViewController.h"

@interface ViewController ()
/** 背景图片 */
@property (nonatomic,weak) UIImageView * imageView;
/** textView */
@property (nonatomic,weak) UITextView * textView;
/** 线程的强引用 */
@property (nonatomic,strong) NSThread * thread;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self textView];
    self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [self.thread start];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
}

- (void)run {
    NSLog(@"---run---");
}

- (void)test {
    NSLog(@"---test---");
}

解释:当执行之后会打印---run---。但是永远也不会执行打印---test---。因为self.thread虽然是已经创建,并且是全局的强引用,但是当---run---方法执行完成之后self.thread就出在消亡状态

解决办法:当执行到run方法中,将这个全局的变量线层挂起,当下次用到的时候再调用

#import "ViewController.h"

@interface ViewController ()
/** 背景图片 */
@property (nonatomic,weak) UIImageView * imageView;
/** textView */
@property (nonatomic,weak) UITextView * textView;
/** 线程的强引用 */
@property (nonatomic,strong) NSThread * thread;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self textView];
    self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [self.thread start];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
}

- (void)run {
    NSLog(@"---run---");

    // 在这里执行的时候让线程挂起
    [[NSRunLoop currentRunLoop] run];
    // 作用跟桑卖弄挂起是一样的
    //[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

- (void)test {
    NSLog(@"---test---");
}

解释:这时候点击仍然是没有任何打印test的。因为这时候虽然是创建了,但是在[[NSRunLoop currentRunLoop] run];的时候,我们没有向RunLoop添加任何内容,没有内容就会自动退出线程。

解决办法

在RunLoop中添加内容,就会等待不会退出,

-(void)run {
    NSLog(@"---run---");

    // 在这里执行的时候让线程挂起
    // port:相当于加行一个source但是我们用不上,可随便间加
    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

在子线程中检测信息有三种方法

第一种实现起来比较复杂


    - (void)viewDidLoad {
        [super viewDidLoad];

        // 创建一个线程
        self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
        // 开启一个线程
        [self.thread start];

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

    }

    // 线程执行的内容
    - (void)run {
        NSLog(@"---run---");
        // 设置定时器,检测想要检测的内容
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(chick) userInfo:nil repeats:YES];
        // 在这里执行的时候让线程挂起
        // port:相当于加行一个source但是我们用不上,可随便间加
        [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    }

    // 在线程中添加操作
    - (void)chick {
        [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
    }

    // 这里写需要执行的检查代码
    - (void)test {
        NSLog(@"【检查网络连接】%@",[NSThread currentThread]);
    }

第二种

- (void)viewDidLoad {
    [super viewDidLoad];
    self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    // 开启一个线程
    [self.thread start];
}
    - (void)run {
   @autoreleasepool{
        NSTimer * timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(check) userInfo:nil repeats:YES];

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

    - (void)check {
        NSLog(@"【检查网络连接】%@",[NSThread currentThread]);
    }

第三种

- (void)viewDidLoad {
    [super viewDidLoad];
    self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    // 开启一个线程
    [self.thread start];
}
- (void)run {
    @autoreleasepool {
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(check) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] run];
    }
}

- (void)check {
    NSLog(@"【检查网络连接】%@",[NSThread currentThread]);
}

GC定时器(很精确)

#import "ViewController.h"

@interface ViewController ()
/** 定时器(这里不用带*,因为dispatch_source_t就是个类,内部已经包含了*) */
@property (nonatomic, strong) dispatch_source_t timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

//    dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
//    
//    dispatch_after(when, dispatch_get_main_queue(), ^{
//        NSLog(@"-------");
//    });
}

int count = 0;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 获得队列
//    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_queue_t queue = dispatch_get_main_queue();

    // 创建一个定时器(dispatch_source_t本质还是个OC对象)
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

    // 设置定时器的各种属性(几时开始任务,每隔多长时间执行一次)
    // GCD的时间参数,一般是纳秒(1秒 == 10的9次方纳秒)
    // 何时开始执行第一个任务
    // dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC) 比当前时间晚3秒
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC);
    dispatch_source_set_timer(self.timer, start, interval, 0);

    // 设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        NSLog(@"------------%@", [NSThread currentThread]);
        count++;

//        if (count == 4) {
//            // 取消定时器
//            dispatch_cancel(self.timer);
//            self.timer = nil;
//        }
    });

    // 启动定时器
    dispatch_resume(self.timer);
}
@end

results matching ""

    No results matching ""