Runloop

模式:

RunLoop 在同一段时间只能且必须在一种特定的模式下运行。

RunLoop 有四种模式:

• NSDefaultRunLoopMode:默认模式,表示应用程序空闲,绝大多数的事件响应都是在这种模式:定时器

• UITrackingRunLoopMode:滚动模式

• UIInitializationRunLoopMode:私有的,App启动时

• NSRunLoopCommonModes:默认包含1,2两种模式



定时器和RunLoop

- (void)viewDidLoad {

[super viewDidLoad];

NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fire) userInfo:nil repeats:YES];

// 添加到运行循环

// NSDefaultRunLoopMode : 默认模式,表示应用程序空闲,绝大多数的事件响应都是在这种模式:定时器

// UITrackingRunLoopMode : 滚动模式, 只有滚动模式下才会触发定时器回调。

// NSRunLoopCommonModes : 默认包含1,2两种模式

[[NSRunLoop currentRunLoop] addTimer:timer forMode: NSRunLoopCommonModes];

}

- (void)fire {

// 模拟睡眠

// 在iOS9.0之前,线程休眠的时候,runLoop 不响应任何事件,开发中不建议使用。

//    [NSThread sleepForTimeInterval:1.0];

static int num = 0;

///  耗时操作

for (int i = 0; i < 1000 * 1000; ++i) {

[NSString stringWithFormat:@"hello - %d", i];

}

NSLog(@"%d", num++);

}

运行测试,会发现卡顿非常严重。

Ø 将时钟添加到其他线程工作

- (void)viewDidLoad {

[super viewDidLoad];

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimer) object:nil];

[thread start];

}

- (void)startTimer {

NSLog(@"startTimer = %@",[NSThread currentThread]);

NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fire) userInfo:nil repeats:YES];

// 添加到运行循环

// NSDefaultRunLoopMode : 默认模式,表示应用程序空闲,绝大多数的事件响应都是在这种模式:定时器

// UITrackingRunLoopMode : 滚动模式, 只有滚动模式下才会触发定时器回调。

// NSRunLoopCommonModes : 默认包含1,2两种模式

// 在实际开发中,不建议将定时器的运行循环模式设置为NSRunLoopCommonModes,在有耗时操作的时候会影响流畅度。

[[NSRunLoop currentRunLoop] addTimer:timer forMode: NSRunLoopCommonModes];

// runLoop最主要的作用:监听事件

// 每一个线程都会有一个 runLoop,默认情况下,只有主线程的 runLoop 是开启的,子线程的 runLoop 是不开启。

// 启动当前线程的runLoop -- 是一个死循环

// 使用下面方法启动,没办法在某一条件成立后手动停止runLoop,只能由系统停止。

//    [[NSRunLoop currentRunLoop] run];

CFRunLoopRun();

NSLog(@"come here");

}

- (void)fire {

// 模拟睡眠

// 在iOS9.0之前,线程休眠的时候,runLoop 不响应任何事件,开发中不建议使用。

//    [NSThread sleepForTimeInterval:1.0];

static int num = 0;

///  耗时操作

for (int i = 0; i < 1000 * 1000; ++i) {

[NSString stringWithFormat:@"hello - %d", i];

}

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

if (num == 2) {

NSLog(@"停止RunLoop");

// 停止RunLoop

CFRunLoopStop(CFRunLoopGetCurrent());

}

}

注意:主线程的运行循环是默认启动的,但是子线程的运行循环是默认不工作的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、什么是runloop 字面意思是“消息循环、运行循环”。它不是线程,但它和线程息息相关。一般来讲,一个线程一次...
    WeiHing阅读 8,302评论 11 111
  • Run loop 剖析:Runloop 接收的输入事件来自两种不同的源:输入源(intput source)和定时...
    Mitchell阅读 12,630评论 17 111
  • 来源:击水湘江 链接:http://www.jianshu.com/p/536184bfd163 实例化讲解Run...
    __Lex阅读 290评论 0 2
  • runtime 和 runloop 作为一个程序员进阶是必须的,也是非常重要的, 在面试过程中是经常会被问到的, ...
    made_China阅读 1,269评论 0 7
  • runtime 和 runloop 作为一个程序员进阶是必须的,也是非常重要的, 在面试过程中是经常会被问到的, ...
    SOI阅读 22,020评论 3 63

友情链接更多精彩内容