美文网首页专注iOS开发的小渣渣
用RunLoop监听运行循环

用RunLoop监听运行循环

作者: 蜗蜗牛在奔跑 | 来源:发表于2017-04-19 10:06 被阅读47次

//  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监听运行循环

    // ViewController.m // 运行循环RunLoop // // Created by xue o...

  • runloop

    Runloop-- 运行循环(死循环) 目的:1、保证runloop所在线程不退出2、负责监听事件(触摸 时钟 ...

  • iOS RunLoop 相关面试题

    RunLoop监听 Runloop运行逻辑

  • IOSRunLoop_运行循环(NSTimer)

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

  • RunLoop详解

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

  • NSRunLoop--线程

    NSRunLoop其实本质就是死循环;作用:Runloop--运行循环 1.保证程序不退出 2.负责监听事件、触摸...

  • iOS RunLoop简单理解与运用

    二话不说先上我麦来压压惊 什么是RunLoop? RunLoop顾名思义运行着的循环,而且是一个死循环,他负责监听...

  • Runloop

    Runloop 运行循环 --- > 死循环 目的: 1.保证当前线程不退出 2.负责监听事件 ios中的网络事件...

  • iOS 关于RunLoop

    一 runloop 解释 1. 运行循环(死循环). 2.负责处理监听事件 (如:触摸屏幕,时钟事件,网络事件等)...

  • RunLoop学习与总结

    RunLoop一个运行循环保持程序的持续运行监听处理 APP 各种事件(触摸,定时器,selector)节省 CP...

网友评论

    本文标题:用RunLoop监听运行循环

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