美文网首页iOS开发iOS Developer
IOSRunLoop_运行循环(NSTimer)

IOSRunLoop_运行循环(NSTimer)

作者: _CLAY_ | 来源:发表于2017-04-04 21:53 被阅读91次

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

相关文章

  • IOSRunLoop_运行循环(NSTimer)

    RunLoop 运行循环 (NSTimer) 目的: 保证程序不退出 负责监听事件,触摸,时钟,网络事件 如果没...

  • NSTimer和运行循环

    //1.本质上就是创建一个时钟,以默认的模式添加到运行循环中 [NSTimer scheduledTimerWit...

  • 52个有效方法(52) - 别忘了NSTimer会保留其目标对象

    计时器要和“运行循环”(run loop)相关联,运行循环到时会触发任务。创建NSTimer时,可以将其“预先安排...

  • NSTimer会保留其目标对象(一)

    计时器要和“运行循环”(run loop)相关联,运行循环到时会触发任务。创建NSTimer时,可以将其“预先安排...

  • NSTimer 定时器

    NSTimer是基于runloop进行消息分派,调度NSTimer,其实是要求当前运行循环在某个特定的时间分配某个...

  • 运行循环

    iOS运行循环 NSTimer使用 停止计时器 可重用计时器

  • RunLoop

    RunLoop顾名思义运行循环,在程序运行过程中循环做一些事情,比如:定时器(NSTimer)、GCD Async...

  • KVC键值编码

    运行循环(runLoop) —自动释放池丶滚动视图丶(NSTimer) >全称是Key-Value coding即...

  • iOS定时器循环引用分析及完美解决方案

    目录 1.NSTimer导致的循环引用分析2.NSTimer循环引用解决思路误区3.NSTimer循环引用解决方案...

  • NSTimer中的NSRunloop

    NSTimer与NSRunloop平时的运用 一, 简单的了解NSRunloop 从字面上看:运行循环、跑圈 其实...

网友评论

    本文标题:IOSRunLoop_运行循环(NSTimer)

    本文链接:https://www.haomeiwen.com/subject/tvbzottx.html