Skip to content

Commit 0702abe

Browse files
committed
Runloop 中加一个具体例子
1 parent 3386da0 commit 0702abe

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

source/iOS/ObjC-Basic/Runloop.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,15 @@ Runloop 通过监控 Source 来决定有没有任务要做,除此之外,我
5959

6060
iOS 中公开暴露出来的只有 NSDefaultRunLoopMode 和 NSRunLoopCommonModes。 NSRunLoopCommonModes 实际上是一个 Mode 的集合,默认包括 NSDefaultRunLoopMode 和 NSEventTrackingRunLoopMode。
6161

62+
### Runloop 的坑
63+
64+
日常开发中,与 runLoop 接触得最近可能就是通过 NSTimer 了。一个 Timer 一次只能加入到一个 RunLoop 中。我们日常使用的时候,通常就是加入到当前的 runLoop 的 default mode 中,而ScrollView在用户滑动时,主线程RunLoop会转到UITrackingRunLoopMode。而这个时候,Timer就不会运行。
65+
66+
有如下两种解决方案:
67+
68+
- 第一种: 设置RunLoop Mode,例如NSTimer,我们指定它运行于 NSRunLoopCommonModes ,这是一个Mode的集合。注册到这个 Mode 下后,无论当前 runLoop 运行哪个 mode ,事件都能得到执行。
69+
- 第二种: 另一种解决Timer的方法是,我们在另外一个线程执行和处理 Timer 事件,然后在主线程更新UI。
70+
6271
#### 参考资料
6372

6473
* https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW1

0 commit comments

Comments
 (0)