以+scheduledTimerWithTimeInterval...的方式觸發的timer,在滑動頁面上的列表時,timer會暫定回調,為什麽?如何解決?
阿新 • • 發佈:2017-09-22
指定 val timer 運行模式 sch 發的 滑動頁面 循環 oop
- 這裏強調一點:在主線程中以+scheduledTimerWithTimeInterval...的方式觸發的timer默認是運行在
NSDefaultRunLoopMode
模式下的,當滑動頁面上的列表時,進入了UITrackingRunLoopMode
模式,這時候timer就會停止 -
可以修改timer的運行模式為
NSRunLoopCommonModes
,這樣定時器就可以一直運行了 -
以下是我的筆記補充:
- 在
子線程
中通過scheduledTimerWithTimeInterval:...方法
來構建NSTimer- 方法內部已經創建NSTimer對象,並加入到RunLoop中,運行模式為NSDefaultRunLoopMode
- 由於Mode有timer對象,所以RunLoop就開始監聽定時器事件了,從而開始進入運行循環
- 這個方法
僅僅
是創建RunLoop對象,並不會
主動啟動RunLoop,需要再調用run方法
來啟動
-
如果在
主線程
中通過scheduledTimerWithTimeInterval:...方法
來構建NSTimer,就不需要主動啟動RunLoop對象,因為主線程的RunLoop對象在程序運行起來就已經被啟動了// userInfo參數:用來給NSTimer的userInfo屬性賦值,userInfo是只讀的,只能在構建NSTimer對象時賦值 [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(run:) userInfo:@"ya了個hoo" repeats:YES]; // scheduledTimer...方法創建出來NSTimer雖然已經指定了默認模式,但是【允許你修改模式】 [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; // 【僅在子線程】需要手動啟動RunLoop對象,進入運行循環 [[NSRunLoop currentRunLoop] run];
- 在
以+scheduledTimerWithTimeInterval...的方式觸發的timer,在滑動頁面上的列表時,timer會暫定回調,為什麽?如何解決?