美文网首页iOS Developer
运行循环RunLoop

运行循环RunLoop

作者: 蜗蜗牛在奔跑 | 来源:发表于2017-04-24 11:57 被阅读18次
//
//  ViewController.m
//  运行循环RunLoop
//
//  Created by xue on 2017/4/19.
//  Copyright © 2017年 liangxue. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
//    
//    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
//
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
    
    [self addRunloopObserver];
    
    // Do any additional setup after loading the view, typically from a nib.
}

//什么也不干,只是为了让runloop起来
- (void)timerMethod{
    
}
//千万不要做耗时操作
- (void)updateTimer{
    
    static int num = 0;
    [NSThread sleepForTimeInterval:1.0];

    NSLog(@"%@   %d",[NSThread currentThread],num++);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 监听runloop
- (void)addRunloopObserver{
    //获取当前runloop
    CFRunLoopRef runloop = CFRunLoopGetCurrent();
    //定义一个上下文
    CFRunLoopObserverContext context = {
        0,
        (__bridge void *)self,
        &CFRetain,
        &CFRelease,
        NULL
    };
    //定义一个观察者  callback回掉函数
    static CFRunLoopObserverRef defaultObserver;
   defaultObserver  = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, YES, NSIntegerMax - 999, &CallBack, &context);
    
    //添加当前runloop 的观察者
    
    CFRunLoopAddObserver(runloop, defaultObserver, kCFRunLoopDefaultMode);
    
    //释放
    
    CFRelease(defaultObserver);
}
//runloop回掉函数
static void CallBack(){
    
    NSLog(@"lalal");
}
@end

相关文章

  • RunLoop详解

    RunLoop详解 RunLoop运行循环(死循环) RunLoop模式 NSDefaultRunLoopMode...

  • RunLoop概念与响应者链

    一.RunLoop简介 什么是RunLoop? RunLoop就是运行循环,在程序运行的过程中循环做一些事情,如果...

  • 教你如何轻松搞定 Runloop

    认识 Runloop Runloop 就是运行循环,如果没有 Runloop,程序一运行就会退出,有 Runloo...

  • iOS-Runloop1-Runloop

    一. RunLoop相关 什么是Runloop?顾名思义,Runloop就是运行循环,就是在程序运行过程中循环做一...

  • 【iOS】Runloop

    Runloop概念 运行循环(死循环) Runloop作用 保持程序的持续运行 处理app中的各种事件 节省CPU...

  • RunLoop

    RunLoop简介 RunLoop,就是一个运行循环,通过一个内部的运行循环(Event Loop)对事件或者消息...

  • NSRunLoop

    RunLoop运行逻辑 RunLoop面试题: 1、什么是RunLoop? 答:从字面意思上:运行循环、跑圈。 其...

  • 初探Runloop

    1.runloop是什么? runloop 是一个运行循环(死循环); return UIApplicationM...

  • 简单谈谈RunLoop

    1、RunLoop定义 从字面上看,run是运行,执行的意思,loop是循环的意思,其实RunLoop就是运行循环...

  • RunLoop基础

    RunLoop简介 RunLoop运行循环,在程序运行过程中循环做一些事情.如:定时器(Timer)、Perfor...

网友评论

    本文标题:运行循环RunLoop

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