RunLoop的浅析

在说RunLoop前先说一个问题,这是前些天别人问我的。在UI界面上有一个滚动视图,滚动视图中有n张图片,还有一个计时器,从程序启动就开始运行,在后台打印东西,当我们滑动滚动视图中的图片时,计时器会不会继续打印东西?答:不能。

这是为什么?为什么会不打印了?这时我们讨论的问题来了,之所以不能打印是因为对于主线程系统默认为我们创建了一个RunLoop,当我们进行一个操作的时候,另一个命令就处于等待状态,等待上个命令执行完毕。那么RunLoop又是什么呢?

RunLoop你可以用字面意思大概理解下,一个一直运行的循环,对于主线程系统默认为我们创建了一个RunLoop,但是对于自己创建的子线程,我们就得自己去手动创建RunLoop了,你可以在线程内部用[NSRunLoop currentRunLoop]来获取到当前线程的RunLoop(注意:只能先线程内部获取,主线程除外),RunLoop我们常用的Model就是NSDefaultRunLoopMode以及NSRunLoopCommonModes这两种模式,有什么区别呢?我们通过以下代码来一起看一下。

1 - (void)createTimer
2 {
3     timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(viewchanged) userInfo:nil repeats:YES];
4 }

我想上面这句代码都很熟悉了,其实这句代码和下面这段代码是相同效果的

1 - (void)createTimer
2 {
3     timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(viewchanged) userInfo:nil repeats:YES];
4     
5     [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
6 }

那么用上面这段代码来运行的时候滚动视图计时器就会停止运行,当我们滚动视图停止操作的时候,定时器会接着继续运行。那么如何解决这种冲突呢?

我们只需要将RunLoop的模式改下就可以了如下:

1 - (void)createTimer
2 {
3     timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(viewchanged) userInfo:nil repeats:YES];
4     
5     [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
6 }

我们在创建计时器的时候考虑下如果单独就只有一个操作的时候用默认的scheduledTimerWithTime方法,但是对于多操作的时候我们就需要timerWithTime方法来创建计时器了。

希望可以对于小白有所帮助,不足之处求大神指教!!!

 

posted @ 2016-07-15 13:41  帝丿奎哥  阅读(180)  评论(0编辑  收藏  举报