IOSRunLoop_运行循环(NSTimer)

RunLoop 运行循环 (NSTimer)

目的:

  • 保证程序不退出
  • 负责监听事件,触摸,时钟,网络事件
  • 如果没有事情发生,会让程序进入到休眠状态
    ViewController.m
#import "ViewController.h"

@interface ViewController ()
@property (nonatomic,assign,getter=isfinish) BOOL finish;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _finish = YES;
    
    //子线程
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //NSTimer 之所以能被监听是因为它已经被加入到RunLoop中
        
        //初始化NSTimer---1
        //    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeup) userInfo:nil repeats:YES];
        
        //初始化NSTimer---2
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeup) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        
        while (self.finish) {
            //开启运行循环
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceReferenceDate:0.1]];
        }
        NSLog(@"当RunLoop停止的时候线程会被销毁");
        //看一下在那个线程
        NSLog(@"%@",[NSThread currentThread]);
    });
    //模式:
    /*
     1.NSDefaultRunLoopMode  -- 时钟(建议),网络事件
     2.UITrackingRunLoopMode -- 用户交互(优先处理)
     3.NSRunLoopCommonModes  -- 它并不是一个真正的模式(只是一个占位)
     可以解决滑动页面NSTimer停止的问题,但是进行耗时操作界面会卡顿.
     
     注意:子线程默认是不开启RunLoop的!!!那么子线程的代码执行完毕后就会被回收!!!
     */
    
}

- (void)timeup {
    NSLog(@"时间到%@",[NSThread currentThread]);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    _finish = NO;
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容